c# – 如何使用具有二维数组的LINQ
发布时间:2020-12-16 02:04:22 所属栏目:百科 来源:网络整理
导读:我有一个二维字节数组,看起来像这样: 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 0 1 0 1 数组中的每个值只能是0或1.上面的简化示例显示了4行,每行有5列.我试图弄清楚如何使用LINQ将索引返回到具有最大数量1s的行,在上面的示例中应该返回1. 以下非LINQ C#代码解决了
我有一个二维字节数组,看起来像这样:
数组中的每个值只能是0或1.上面的简化示例显示了4行,每行有5列.我试图弄清楚如何使用LINQ将索引返回到具有最大数量1s的行,在上面的示例中应该返回1. 以下非LINQ C#代码解决了这个问题: static int GetMaxIndex(byte[,] TwoDArray) { // This method finds the row with the greatest number of 1s set. // int NumRows = TwoDArray.GetLength(0); int NumCols = TwoDArray.GetLength(1); int RowCount,MaxRowCount = 0,MaxRowIndex = 0; // for (int LoopR = 0; LoopR < NumRows; LoopR++) { RowCount = 0; for (int LoopC = 0; LoopC < NumCols; LoopC++) { if (TwoDArray[LoopR,LoopC] != 0) RowCount++; } if (RowCount > MaxRowCount) { MaxRowCount = RowCount; MaxRowIndex = LoopR; } } return MaxRowIndex; } static void Main() { byte[,] Array2D = new byte[4,5] { { 0,1 },{ 1,1,0 },{ 0,1 } }; int MaxInd = GetMaxIndex(Array2D); Console.WriteLine("MaxInd = {0}",MaxInd); } 所以,我的问题是: >如何使用LINQ来解决这个问题,并且在这里使用LINQ会比使用上面的非LINQ代码效率低吗? 解决方法
使用LINQ的多维数组很难处理,但是你可以这样做:
var arr = new [,] { { 0,1 } }; var data = Enumerable.Range(0,4) .Select( row => new { index = row,count = Enumerable.Range(0,5).Select(col => arr[row,col]).Count(x => x == 1) }) .OrderByDescending(x => x.count) .Select(x => x.index) .First(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |