0

Possible Duplicate:
Get sum of two columns in one LINQ query

I need to know how to write an LINQ Query that will give me the same results as this SQL Query :

select sum(col1) as [col1] , sum(col2) as [col2] , sum(col1)/sum(col2) as [col3], col4 as [col4] 
from some_table 
group by col4
Community
  • 1
  • 1
Matan L
  • 997
  • 3
  • 14
  • 35

3 Answers3

4

Or with Lambda, i am assuming some_table is an Entity or Repository .. etc.

some_table.GroupBy( row => row.col4).Select( row => new
{
    col1 = row.Sum(x => x.col1), 
    col2 = row.Sum(x => x.col2),
    col3 = row.Sum(x => x.col1) / row.Sum(x => x.col2),
    col4 = row.Key
}); 
Stan R.
  • 15,757
  • 4
  • 50
  • 58
3

Full props go to Steven for this answer: https://stackoverflow.com/a/2432348/211627

from row in some_table
group row by row.col4 into g
select new
{
    col1 = g.Sum(x => x.col1), 
    col2 = g.Sum(x => x.col2),
    col3 = g.Sum(x => x.col1) / g.Sum(x => x.col2),
    col4 = g.Key
};
Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123
2

This is assuming that your table is some sort of entity. This will put it into an Anonymous Type, but can be used to create an object of your own type also.

myInitialCollection.GroupBy(x => x.Col4).Select(x => 
    new { 
            col1 = x.Sum(y => y.Col1), 
            col2 = x.Sum(y => y.Col2), 
            col3 = (x.Sum(y => y.col1) / x.Sum(y => y.col2)), 
            col4 = x.Key
    });
Dave Zych
  • 21,581
  • 7
  • 51
  • 66