Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq group by query

Tags:

Trying to work out a linq query and was wondering if you guys could help.

I have a list of objects foo and each foo object has a list of bar. bar has an active date and a numeric value. for example

foo    bar -> 01/02/05, 10000    bar -> 04/06/10, 30023 foo    bar -> 30/01/02, 23494 

And I want to write a linq query that will return me a distinct list of dates and the summed total for that date

It may be that its friday, but I'm drawing a blank.

Thanks in advance

like image 333
mat-mcloughlin Avatar asked Mar 18 '11 15:03

mat-mcloughlin


People also ask

What does GroupBy return in LINQ?

A LINQ query can end with a GroupBy or Select clause. The result of GroupBy operators is a collection of groups. For example, GroupBy returns IEnumerable<IGrouping<TKey,Student>> from the Student collection: Return type of GroupBy()

What is GroupBy in C#?

The group clause returns a sequence of IGrouping<TKey,TElement> objects that contain zero or more items that match the key value for the group. For example, you can group a sequence of strings according to the first letter in each string.

What is the return type of GroupBy method?

The GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) method returns a collection of IGrouping<TKey,TElement> objects, one for each distinct key that was encountered.


1 Answers

Looks like you want:

var query = from foo in list             from bar in foo.Bars             group bar.Value by bar.Date into dates             select new { Date = dates.Key, Sum = dates.Sum() }; 
like image 122
Jon Skeet Avatar answered Sep 23 '22 03:09

Jon Skeet