无论如何使用LINQ获取二维数组的每列最大值?
假设我有以下内容:
var arrays = new double[5,100]();
Run Code Online (Sandbox Code Playgroud)
我想,以获得最大的arrays[0,:],arrays[1,:]...... arrays[4,:].如何使用LINQ来做到这一点?
我可以使用这种方法
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;
}
Run Code Online (Sandbox Code Playgroud)
但我更喜欢更简洁的做事方式.
我认为没有内置的方法可以从多维数组中获取行。不过,您可以编写一个扩展方法:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需使用“普通”LINQ:
var max = array.Row(i).Max();
Run Code Online (Sandbox Code Playgroud)
我想你总是可以使用Enumerable.Range索引访问的紧凑形式:
public static double GetMax(double[,] arr, int rowIndex)
{
return (from col in Enumerable.Range(0, arr.GetLength(1))
select arr[rowIndex, col]).Max();
}
Run Code Online (Sandbox Code Playgroud)
如果你想为所有行获取:
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();
}
Run Code Online (Sandbox Code Playgroud)