如何用C#Linq编写这个

时间:2012-02-23 08:35:31

标签: c# .net linq linq-to-sql

我不是Linq的专业人士,而是试图理解。如何用C#

编写这段代码(用VB编写)
  

Dim x =来自db.YourClass _中的p

     

其中p.fl1 = cn1且p.f12 = cn2

     

选择_

     

sum1 = x.Sum(Function(y)y.fl1),_

     

sum2 = x.Sum(函数(y)y.fl2),_

     

sum3 = x.Sum(函数(y)y.fl3)

我想要实现的是这个,

  

选择sum(fl1),sum(fl2),sum(fl3)

     

其中fl1 = cn1且fl2 = cn2

The above sample found here

3 个答案:

答案 0 :(得分:4)

var x =
    from p in db.YourClass
    where p.fl1 == cn1 && p.fl2 == cn2
    select p;


var sum1 = x.Sum(y => t.fl1);
var sum2 = x.Sum(y => t.fl2);
var sum3 = x.Sum(y => t.fl3);

答案 1 :(得分:2)

var x = from p in db.YourClass 
        where p.fl1 == cn1 && p.f12 == cn2
        select p;

  var sum1 = x.Sum(y=>y.fl1), 

  var sum2 = x.Sum(y=>y.fl2), 

  var sum3 = x.Sum(y=>y.fl3)

编辑:在一个查询中,我认为这可以很快地运作:

var x = (from p in db.YourClass 

        select new 
        {
         s1 = db.YourClass.Where(y=> y.fl1 == cn1 && y.f12 == cn2).Sum(y=>y.fl1),
         s2 = db.YourClass.Where(y=> y.fl1 == cn1 && y.f12 == cn2).Sum(y=>y.fl2),
         s3 = db.YourClass.Where(y=> y.fl1 == cn1 && y.f12 == cn2).Sum(y=>y.fl3)
        }).First();

 int sum1 = x.s1, sum2 = x.s2, sum3 = x.s3;

答案 2 :(得分:1)

你可以使用lambda表达式,

public class Sums
{
   public int Sum1{get;set;}
   public int Sum2{get;set;}
   public int Sum3{get;set;}
}

var list = db.YourClass.Where(x=>x.fl1==cn1 && x.f12==cn2).Select(y => 
                                new Sums{ 
                                    Sum1 = y.Sum(z=>z.fl1),
                                    Sum2 = y.Sum(z=>z.fl2),
                                    Sum3 = y.Sum(z=>z.fl3)
                                }).ToList();