I have an IEnumerable<IEnumerable<double>>
which can basically be thought of as a 2D array of doubles and what I want to do is get a 1D array (or list or whatever) that is the total for all the columns of my original collection. In other words, if I had:
1 2 3 4
2 3 1 6
3 4 5 6
-------------
6 9 9 16
I'd want the last line (which is not part of the original collection, obviously).
Is there a simple way to do this with LINQ so that I don't have to loop over the whole thing? I know I can use .Sum
to total one row or one column, but I want to total each row.
I've seen some other questions (mostly dealing with database queries) that suggest using group
but that didn't seem to work for me. I tried this:
var totals = from p in toTotal
group p by 1 into g
select g.Sum(t => t.First());
But that just totals everything.
Is there a clever way to do this?
Edit: for example, if toTotal
was defined as:
List<List<double>> toTotal = new List<List<double>>() {
new List<double> {1, 2, 3, 4},
new List<double> {2, 3 , 1, 6},
new List<double> {3 , 4, 5 , 6}
};