简体   繁体   English

LINQ查找二维锯齿状数组最小值,返回索引

[英]c# - LINQ find 2D jagged array minimum, return index

I have a standard 2D jagged array int[][] arr . 我有一个标准的2D锯齿状数组int[][] arr

Let's call i and j the indices for row and column. 让我们将ij称为行和列的索引。

I'd like to retrieve via LINQ the indices i and j which points to the minimum of the matrix. 我想通过LINQ检索指向矩阵最小值的索引ij

An idea of what I am trying to achieve is bri 我想要达到的目标是

from num in arr
where min = (from num in arr select min(num))
select i, j

You can use the the overloads of SelectMany and Select that include the index and then OrderBy and First to get one of the sets of indexes with the minimum value. 您可以使用SelectManySelect的重载(包括索引),然后使用OrderByFirst重载来获取具有最小值的一组索引。

var min = arr.SelectMany((subArr, i) => subArr.Select((value, j) => new { i, j, value }))
    .OrderBy(x => x.value)
    .First();
int firstIndex = min.i;
int secondIndex = min.j;

You can also do this: 您也可以这样做:

var result = from i in Enumerable.Range(0, arr.Length)
             from j in Enumerable.Range(0, arr[i].Length)
             orderby arr[i][j]
             select new { i, j };
var r = result.FirstOrDefault();// here is the indexes of min value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM