суббота, 29 марта 2014 г.

LINQ Group and Sum table

Copy from Here:

http://social.msdn.microsoft.com/Forums/en-US/3b13432a-861e-45f0-8c25-4d54622fbfb4/linq-group-and-sum-table

schedules:
empid    hours    date    weekending
5311      4         1/3/08   1/5/2008
5311      5         1/3/08   1/5/2008
9983      1         1/3/08   1/5/2008
9983      2         1/3/08   1/5/2008
5311      3         1/7/08   1/12/2008
5311      7         1/8/08   1/12/2008
I want to generate this:
5311       1/5/2008      9
9983       1/5/2008      3
5311       1/12/2008    10

from s in db.Schedules
group s by new {s.empid, s.weekending} into g
select new { g.Key.empid, g.Key.weekending, g.Sum(s => s.hours) };
The interesting part here is that you are grouping by two key conditions.  Yet a LINQ group by operator can only group by one condition.  So what you have to do is combine the conditions into a single anonymous type.  Once you've grouped, you now have a new variable 'g' instead of 's'.  Each instance of 'g' contains one of the group key values and a collection of the items in the group.  You can then use the Sum() operator on the collection to compute the sum over the hours. 

Комментариев нет:

Отправить комментарий