Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

column operations on jagged arrays (sum, average, other functions) with Linq

Assuming we have a jagged array with equal length item arrays (i.e. ignore catching out of ranges):

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

what is the most elegant way to apply c# Linq to perform column operations. Example results for simple column operations Sum and Average:

Sum() column result: int[] {12, 27, 15 } Average() column result: int[] {4, 9, 5 } ...any other similar extension method that operates on a column.

The closest related question I could find is here.

Thanks for the answers, I have accepted Jay's answer and also posted a similar but much more complicated aggregation of columns on an Enumerable question here.

like image 400
Keith Avatar asked May 08 '14 12:05

Keith


2 Answers

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

Substitute Sum with Average etc.

like image 109
Jay Avatar answered Oct 08 '22 20:10

Jay


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

for all column computation use Enumerable.Range

var res = Enumerable.Range(0, 3).Select(columnIndex => GetColumnValues(jaggedArray, columnIndex).Sum());
like image 3
Vladimir Sachek Avatar answered Oct 08 '22 20:10

Vladimir Sachek