How to use linq to find the minimum [duplicate]
Solution 1:
Use Aggregate:
items.Aggregate((c, d) => c.Score < d.Score ? c : d)
As suggested, exact same line with more friendly names:
items.Aggregate((minItem, nextItem) => minItem.Score < nextItem.Score ? minItem : nextItem)
Solution 2:
Try items.OrderBy(s => s.Score).FirstOrDefault();
Solution 3:
Have a look at the MinBy extension method in MoreLINQ (created by Jon Skeet, now principally maintained by Atif Aziz).
MinBy documentation
MinBy source code (it's pretty straightforward and has no dependencies on other files).
Solution 4:
This can be solved with a little simple iteration:
float minScore = float.MaxValue;
A minItem = null;
foreach(A item in items)
{
if(item.Score < minScore)
minItem = item;
}
return minItem;
It's not a nice LINQ query, but it does avoid a sorting operation and only iterates the list once, as per the question's requirements.