Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and Sum a List<object[]>

Tags:

c#

lambda

linq

I have this List<object[]>

List<object[]> olst = new List<object[]>();

olst.Add(new object[] { "AA1", 1 });
olst.Add(new object[] { "AA2", 1 });
olst.Add(new object[] { "AA2", 1 });
olst.Add(new object[] { "AA1", 1 });
olst.Add(new object[] { "AA1", 1 });

From olst, I need to produce a new List<object> to hold this:

"AA1", 3
"AA2", 2

In other words, I need to group olst[x][0] and sum up olst[x][1].
I could use a for loop, but I was hoping someone could help me using lambda expressions and/or linq to accomplish this.

like image 804
Administrateur Avatar asked Dec 19 '12 22:12

Administrateur


2 Answers

Use GroupBy and Select:

List<object[]> newList = olst
    /* Group the list by the element at position 0 in each item */
    .GroupBy(o => o[0].ToString())
    /* Project the created grouping into a new object[]: */
    .Select(i => new object[]
    {
        i.Key,
        i.Sum(x => (int)x[1])
    })
    .ToList();
like image 58
Andrew Whitaker Avatar answered Sep 24 '22 19:09

Andrew Whitaker


This will turn you list into a dictionary mapping from the first value to the sum of the second values with the same first value.

var result = olst.GroupBy(entry => (String)entry[0])
                 .Select(group => new Object[]
                                  {
                                      group.Key,
                                      group.Sum(item => (Int32)item[1])
                                   })
                 .ToList();

I missed the part stating the the result should be of type List<Object> containing Object[]. It would help if the downvoters would leave a comment about the why. ;)

like image 1
Daniel Brückner Avatar answered Sep 23 '22 19:09

Daniel Brückner