I have a class A { public float Score; ... }
and an IEnumerable<A> items
and would like to find the A
which has minimal score.
Using items.Min(x => x.Score)
gives the minimal score and not the instance with minimal score.
How can I get the instance by iterating only once through my data?
Edit: So long there are three main solutions:
Writing an extension method (proposed by Svish). Pros: Easy to use and evaluates Score only once per item. Cons: Needs an extension method. (I choosed this solution for my application.)
Using Aggregate (proposed by Daniel Renshaw). Pros: Uses a built-in LINQ method. Cons: Slightly obfuscated to the untrained eye and calls evaluator more than once.
Implementing IComparable (proposed by cyberzed). Pros: Can use Linq.Min directly. Cons: Fixed to one comparer - can not freely choose comparer when performing the minimum computation.
In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.
To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key). Where(g => g.
The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With