Fylax
Fylax

Reputation: 1128

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

I have a standard 2D jagged array int[][] arr.

Let's call i and j the indices for row and column.

I'd like to retrieve via LINQ the indices i and j which points to the minimum of the matrix.

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

Upvotes: 3

Views: 1357

Answers (2)

ocuenca
ocuenca

Reputation: 39356

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

Upvotes: 5

juharr
juharr

Reputation: 32296

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.

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;

Upvotes: 3

Related Questions