We help IT Professionals succeed at work.

Linq->EF lambda syntax for sum & group by

Alw1n
Alw1n asked
on
900 Views
Last Modified: 2012-05-31
Hi,
I am struggling with the EF lambda syntax for the following 2 traditional SQL's:

1. select sum(FIELD1), sum(FIELD2) from MYTABLE where FIELD3 = 3
2. select FIELD1, sum(FIELD2), sum(FIELD3) from MYTABLE group by FIELD1

I kinda get the basics of the syntax below but how do I get this all into one data set like the SQL's above would produce?:
        var x = DBContext.MYTABLE.Where(a => a.FIELD3 == 3);
        var d1 = x.Sum(p1 => p1.FIELD1);
        var d2 = x.Sum(p2 => p2.FIELD2);
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Try:

var x = from a in DBContext.MYTABLE
        where a.FIELD3 == 3
        group a by a.FIELD3 into g
        select new
        {
            d1 = g.Sum(p1 => p1.FIELD1),
            d2 = g.Sum(p2 => p2.FIELD2)
        };

Open in new window

Author

Commented:
Thanks kuafmed, that is close but it's not quite the same:

I can't see how to get the sums without using group by in this:
1. select sum(FIELD1), sum(FIELD2) from MYTABLE where FIELD3 = 3

Your example works fine for this sql except that I can't see how to return
FIELD1 along with the 'sums'
2. select FIELD1, sum(FIELD2), sum(FIELD3) from MYTABLE group by FIELD1
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Great, thanks. I didn't think of using a group like 'group a by a into g' because you can SUM in raw SQL without using a group as long as you only SELECT the SUMMED fields
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.