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.
var results = Enumerable.Range(0, jaggedArray[0].Length)
.Select(i => jaggedArray.Sum(a => a[i]))
.ToArray();
Substitute Sum
with Average
etc.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With