How to get object from .Min extension method?
I have a simple struct:
public struct Coord
{
public Coord (int Row, int Column )
{ 开发者_运维技巧/* set values */ }
public int Row { get; }
public int Column { get; }
}
Given:
int [ , ] myArray;
IEnumerable<Coord> myCoords;
I want to select the coordinate with the smallest value and return that coordinate. I can get the smallest value with:
int val = myCoords.Min(c => myArray[c.Row, c.Col]);
How can I get 'Coord' returned instead?
You can't do this very easily in plain LINQ to Objects, unfortunately. You could find the minimum value and then find the Coord
which has that value, but obviously that means going over the data twice.
I have a MinBy
method in MoreLINQ which you could use though:
Coord minCoord = myCoords.MinBy(c => myArray[c.Row, c.Col]);
Another less than elegant answer:
coords.Single( x => array[x.Row, x.Col] == coords.Min(y => array[y.Row,y.Col]));
精彩评论