Column operations on gear arrays (sum, average, other functions) with Linq

Suppose we have a jagged array with arrays of elements of the same length (i.e. ignoring range catching):

int[][] jaggedArray = new int[][] 
{
    new int[] {1, 3, 5},
    new int[] {0, 2, 4},
    new int[] {11,22,6}
};

which is the most elegant way to use C # Linq to do column operations. Examples of results for simple operations of the Sum and average column:

The result of the Sum () column: int [] {12, 27, 15} The average result (): int [] {4, 9, 5} ... any other similar extension method that works with the column.

The closest related question I could find is here .

Thanks for the answers, I accepted Jay's answer and also posted a similar, but much more complex column grouping on the Enumerable question here .

+4
2
  var results = Enumerable.Range(0, jaggedArray[0].Length)
    .Select(i => jaggedArray.Sum(a => a[i]))
    .ToArray();

Sum Average ..

+4
private static IEnumerable<int> GetColumnValues(IEnumerable<int[]> arr, int columnIndex)
{
    return arr.Select(a => a.Skip(columnIndex).FirstOrDefault());
}
...
GetColumnValues(jaggedArray, 1).Sum();

Enumerable.Range

var res = Enumerable.Range(0, 3).Select(columnIndex => GetColumnValues(jaggedArray, columnIndex).Sum());
+3

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


All Articles