开发者

Using LINQ to Obtain Max of Columns for Two Dimensional Arrays

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开发者_StackOverflow[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();


LINQ does not have any methods that cover multi-dimensional arrays.

However, if you can convert it to a list, or maybe roll-your own extensions.


You can use nested "from" statements. Thus iterate through the entire array with range variables representing the respective col/row position within the table. For each of the numbers, you wish to check if it a new max within its row or within its column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜