Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to Obtain Max of Columns for Two Dimensional Arrays

Tags:

c#

linq

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.

like image 923
Graviton Avatar asked Apr 06 '10 04:04

Graviton


2 Answers

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();
}
like image 163
Aaronaught Avatar answered Nov 14 '22 23:11

Aaronaught


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();
like image 40
R. Martinho Fernandes Avatar answered Nov 14 '22 22:11

R. Martinho Fernandes