Let's say I have a simple list structured like the following two-column table:
letter|number
a|1
a|7
b|2
b|5
I would like to have a Linq query that groups by the letter of the column, sums the grouped elements of the column 'number' and additionally returns the total elements in the array. This will result in the following table:
a | 8 | {1,7}
b | 7 | {2,5}
What I have:
public class GroupedRow {
public int number { get; set; }
public string letter { get; set; }
public int[] elements { get; set; }
}
And in the program:
List<GroupedRow> listfromquery = numberletterlist.GroupBy(x => x.letter)
.Select(grp => new GroupedRow() {
number = grp.Sum(x => x.number)
letter = grp.key.letter
};
Even if I see other ways to do this, I would like to do it in 1 linq query (if possible) or another simple quick way.
source
share