5

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.

Community
  • 1
  • 1
Keith
  • 375
  • 2
  • 7
  • 1
    What have you tried? And why do you need to use LINQ, i.e. are other "elegant" solutions not valid? – default May 08 '14 at 12:59
  • Thanks for the comment. Yes sure other options are valid/straight forward of course (I currently do the same in your typical loop) - but am interested in any elegant linq solution to use with a delegate - my attempts looked like the question I liked - i.e. rather messy. – Keith May 08 '14 at 13:07
  • LINQ is much slower than doing the job with two for loops. In performance matter cases, do not use LINQ. – Anthony Dec 19 '17 at 15:06

2 Answers2

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

Substitute Sum with Average etc.

Jay
  • 56,361
  • 10
  • 99
  • 123
3
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());
Vladimir Sachek
  • 1,126
  • 1
  • 7
  • 20