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.
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();
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With