Linq中Select子句中的条件

我有一个方法获取对象列表,然后根据属性的属性和类型返回所有​​属性值。
我在选择值时遇到困难,因为Select取决于条件。
到目前为止我所做的让我能够以我见过的最丑陋的方式获得价值:

public IEnumerable GetValues(List objects) { var allValues = new List(); foreach (var obj in objects) { // Get the PropertyInfo for the obj var properties = GetPropertiesWithTheAttributes(obj); var values = properties.Select(x => new { Value = x.GetValue(obj, null) == null ? string.empty : x.PropertyType.BaseType == typeof(Enum) ? Convert.ToInt32(x.GetValue(obj, null)).ToString() : (x.GetValue(obj, null)).ToString(), ((ReportAttribute) Attribute.GetCustomAttribute(x, typeof(ReportAttribute), false)).Order }) .OrderBy(x => x.Order) .Select(x => x.Value.ToString()) .ToList(); allValues.AddRange(values); } return allValues; } 

在我在这里发布的代码中,我甚至删除了ReportAttribute中DisplayDate属性的检查,该属性validation属性的datetime属性是否显示为date或datetime …

宁静吧!

我只是将其提取为2种方法,并摆脱三元运算符:

  // not sure how to name 'obj' and 'x' without more context private static object GetValue(PropertyInfo obj, PropertyInfo x) { if (x.GetValue(obj, null) == null) return string.Empty; if (x.PropertyType.BaseType == typeof (Enum)) return Convert.ToInt32(x.GetValue(obj, null)); return x.GetValue(obj, null); } private static int GetOrder(PropertyInfo x) { return ((ReportAttribute) Attribute.GetCustomAttribute(x, typeof(ReportAttribute), false)).Order; } 

所以你可以写:

  public IEnumerable GetValues(List objects) { var allValues = new List(); foreach (var obj in objects) { // Get the PropertyInfo for the obj var properties = GetPropertiesWithTheAttributes(obj); var values = properties.Select(x => new { Value = GetValue(obj, x), Order = GetOrder(x) }) .OrderBy(x => x.Order) .Select(x => x.Value.ToString()) .ToList(); allValues.AddRange(values); } return allValues; } 

如果您确实要内联这个,可以在Select to a statement中更改lambda表达式:

 .Select(x => { object value; if (x.GetValue(obj, null) == null) value = string.Empty; else if (x.PropertyType.BaseType == typeof (Enum)) value = Convert.ToInt32(x.GetValue(obj, null)); else value = x.GetValue(obj, null); return new { Value = value, ((ReportAttribute) Attribute.GetCustomAttribute(x, typeof (ReportAttribute), false)). Order }; })