How to write this in C # Linq

I'm not a Linq professional, but trying to figure it out. How to write this code (written in VB) in C #

Dim x = From p to db.YourClass _

Where p.fl1 = cn1 and p.f12 = cn2

Choose _

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

sum2 = x.Sum (Function (y) y.fl2), _

sum3 = x.Sum (Function (y) y.fl3)

I'm trying to achieve this

select the sum (fl1), sum (fl2), sum (fl3)

where fl1 = cn1 and fl2 = cn2

The above example is found here

+4
source share
3 answers
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) 

Edit: In one query, I think this can work quickly:

 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
source
 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); 
+4
source

you can use lambda expression

 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(); 
+1
source

Source: https://habr.com/ru/post/1397980/


All Articles