Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use linq to find the minimum [duplicate]

Tags:

c#

linq

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.

like image 858
Danvil Avatar asked Apr 29 '10 09:04

Danvil


People also ask

How do you find the minimum value in Linq?

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#.

How do I find duplicate records in Linq?

To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key). Where(g => g.

What does => mean in Linq?

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.


1 Answers

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) 
like image 190
Daniel Renshaw Avatar answered Sep 28 '22 02:09

Daniel Renshaw