Total columns of a two-dimensional array

I have one IEnumerable<IEnumerable<double>>, which in principle can be considered as a two-dimensional array of doublings, and what I want to do is get a 1D array (or a list or something else), which is the result for all the columns of my original collection, in other words, if I have had:

1   2   3   4
2   3   1   6
3   4   5   6
-------------
6   9   9   16

I need the last line (which is obviously not part of the original collection).

Is there an easy way to do this with LINQ so I don't have to iterate over all this? I know that I can use .Sumto calculate one row or one column, but I want to output each row.

I saw some other questions (mostly regarding database queries) that suggest using group, but this does not 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’s all.

Is there any reasonable way to do this?

Edit: for example, if toTotaldefined 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}
    };
+3
source share
2 answers

Ok I think I hit him:

var totals = toTotal.Aggregate((prev, next) => prev.Zip(next, (a, b) => a + b));

The trick is that I was looking for a function Fold(or Reduce), but in LINQ it was called Aggregate.

fiddle, @Habib ( ). , ( , ), - , .ToList .Zip, List<List<double>>, , , . toTotal IEnumerable<IEnumerable<double>> .

+3

EDIT:

:

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}
                                };

var res = toTotal.Select(r => r.Select((t, i) => new { Column = i, Value = t }))
                 .SelectMany(r => r)
                 .GroupBy(r => r.Column)
                 .Select(grp => new
                 {
                     Column = grp.Key,
                     Sum = grp.Select(r => r.Value).Sum(),
                 });

foreach (var item in res)
{
    Console.WriteLine("Column: {0}, Sum: {1}", item.Column, item.Sum);
}

:

Column: 0, Sum: 6
Column: 1, Sum: 9
Column: 2, Sum: 9
Column: 3, Sum: 16

Sum IEnumerable toTotal, :

double[]totals = toTotal.Select(r => r.Sum()).ToArray();
+3

Source: https://habr.com/ru/post/1539761/


All Articles