我有一个二维字节数组,看起来像这样:
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.
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代码效率低吗?
> PLINQ可以解决这个问题吗?或者,将任务并行库(TPL)直接用于上述代码并将每行中1的数量计数拆分为单独的线程会更高效,假设每行至少有1,000列吗?
解决方法
使用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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。