m.e*_*son 7 .net c# linq linq-to-entities
我有一个LINQ语句,它将多个列的值相加,每个列都以'HH'开头,尽管还有其他列可用:
//TODO Clean up this mess
var query1 = (from e in Data
where e.SD == date
select e).Select(x => x.HH01 + x.HH16 + x.HH17 + x.HH18 + x.HH19 + x.HH20 + x.HH21 + x.HH22 + x.HH23 +
x.HH24 + x.HH25 + x.HH26 + x.HH27 + x.HH28 + x.HH29 + x.HH30 + x.HH31 + x.HH32 +
x.HH33 + x.HH34 + x.HH35 + x.HH36 + x.HH37 + x.HH38 + x.HH39 + x.HH40 + x.HH41 +
x.HH42 + x.HH43 + x.HH44 +x.HH45 + x.HH46 + x.HH47 + x.HH48 + x.HH49.GetValueOrDefault()+
x.HH50.GetValueOrDefault());
return query1.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
有什么方法可以整理一下吗?我必须做很多变化(用不同的方法),这样就可以清除很多"绒毛".
此外,我想打电话.GetValueOrDefault()
给每一列,但目前我已经把它拿出来了,因为除了最后两列之外的混乱.
建议非常感谢!
我想你可以使用 Reflections 来实现这一点:
double GetHHSum<T>(T x) where T : class
{
double result = 0;
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
if (property.Name.StartsWith("HH"))
sum += Convert.ToSingle(property.GetValue(x)).GetValueOrDefault();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
return (from e in Data
where e.SD == date
select e).ToList().Select(x => GetHHSum(x)).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
代码未测试