[英]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. 让我们将
i
和j
称为行和列的索引。
I'd like to retrieve via LINQ the indices i
and j
which points to the minimum of the matrix. 我想通过LINQ检索指向矩阵最小值的索引
i
和j
。
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. 您可以使用
SelectMany
和Select
的重载(包括索引),然后使用OrderBy
和First
重载来获取具有最小值的一组索引。
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.