linq如何对字段进行循环查询? 表中有a1,a2,……a20这20个字段,想实现分别求和, var qry=(from q in myEntity.tab1 where q.a1!=-999 select q.a1).sum();这样对a1字段求和,但是如何循环这个查询语句求其他字段而不用重复写类似的语句呢?
for(int i=1;i<=20;i++) { var qry=(from q in myEntity.tab1 where Convert.ToInt32(GetPropertyValue(q,"a"+i)) != -999 select GetPropertyValue(q,"a"+i)).sum(); }
------解决方案-------------------- 没有测试过,如果代码有误的话,不要被误导.
C# code
//如果各自条件不同
var qry = from q in myEntity.tab1
select new
{
suma1 = myEntity.tab1.Sum(r=>r.a1 && r.a1!=-999),
suma2 = myEntity.tab1.Sum(r=>r.a1 && r.a2!=-1000)
};
//如果条件都是一样的,如a1!=-999
var qry=from q in myEntity.tabl1
where q.a1!=-999
select new
{
suma1=q.Sum(r=r>r.a1),
suma2=q.Sum(r=r>r.a2),
}
------解决方案--------------------
------解决方案--------------------
C# code
obj.GetType().GetProperties().Sum(x => x.GetValue(obj, null) as int);