Is there anyway to use LINQ to obtain the maximum of each columns for two dimensional arrays?
Assume that I have the following:
var arrays = new double[5,100]();
I want to get the maximum of arrays[0,:]
, arrays[1,:]
.... arrays[4,:]
. How to use LINQ to do it?
I could have use such method
public double GetMax(double[,] arr, int rowIndex)
{
var colCount = arr.GetLength(1);
double max = 0.0;
for(int i=0; i<colCount; i++)
{
max=Math.Max(Math.Abs(arr[rowIndex, i]), max);
}
return max;
}
But I would prefer a more succinct ways of doing things.
I suppose you could always use Enumerable.Range
as a compact form of indexed access:
public static double GetMax(double[,] arr, int rowIndex)
{
return (from col in Enumerable.Range(0, arr.GetLength(1))
select arr[rowIndex, col]).Max();
}
And if you want to get this for all rows:
public static double[] GetMaxForAllRows(double[,] arr, int rowIndex)
{
return (from row in Enumerable.Range(0, arr.GetLength(0))
let cols = Enumerable.Range(0, arr.GetLength(1))
select cols.Max(col => arr[row, col])).ToArray();
}
I don't think there is a built-in way to get a row from a multidimensional array. You can write an extension method though:
public static IEnumerable<T> Row<T>(this T[,] array, int rowIndex)
{
var colCount = array.GetLength(1);
for(int i=0; i<colCount; i++)
{
yield return arr[rowIndex, i];
}
}
And then just use "normal" LINQ:
var max = array.Row(i).Max();
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