Linq中Select子句中的条件
本文关键字:条件 Select Linq 子句 | 更新日期: 2023-09-27 18:15:40
我有一个方法,它获取对象列表,然后根据属性和属性类型返回它们的所有属性值。
我在选择值时遇到了困难,因为Select取决于条件。到目前为止,我所做的使我能够以我见过的最丑陋的方式获得值:
public IEnumerable<string> GetValues(List<ProperyInfo> objects)
{
var allValues = new List<string>();
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属性的检查,该检查验证属性的datetime属性是否将显示为date或datetime…
现在宁静!
我将简单地将其提取为两个方法,并去掉三元操作符:
// 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<string> GetValues(List<PropertyInfo> objects)
{
var allValues = new List<string>();
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
中的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
};
})