Oliver
Oliver

Reputation: 817

Sum elements of list of list using Linq

I have multiple lists of elements which have a date and a value.

firstList has (for example) :

01/01/2013 , 100

02/01/2013 , 444

03/01/2013 , 357

.
.
.

Others lists have more dates and others values

And I add each list in a List<List<myElements>> myListOfLists;

Now, how should I do to have 1 resulting list which contains the sum of all values for each date ?

Thanks,

Upvotes: 0

Views: 3204

Answers (2)

Christos
Christos

Reputation: 53958

I suppose that the definition of myElement is like the following:

public class Item
{
    public DateTime Date { get; set; }
    public double Amount {get; set; }
}

Then your initial list would be of type List<List<Item>>. You can take the sum of Amounts on the same dates, if you flatten your initial list, like below:

List<Item> result = myListOfLists.SelectMany(x => x)
                                   .GroupBy(x => x.Date)
                                   .Select(grp => new Item
                                   { 
                                       Date = grp.Key, 
                                       Amount = grp.Sum(y => y.Amount)
                                   }).ToList();

Here is the link of the test of provided solution.

Upvotes: 2

sloth
sloth

Reputation: 101052

You first have to flatten your list of lists into a single list, then group by the date, then sum each group.

You didn't show any code, but it should be something along:

var result = yourListOfLists.SelectMany(x => x)
                            .GroupBy(x => x.TheDateProperty)
                            .Select(grp => new {key = grp.Key, 
                                                sum = grp.Sum(e => e.TheNumber)});

Upvotes: 1

Related Questions