C # - choose lowest of two values when duplicate key is found
What's the best way to do this with Linq?
I have a list that contains two properties, Number and Percentage.
Sometimes there are duplicate numbers in the list:
-----------------------------
Number: 182 | Percentage: 15%
Number: 182 | Percentage: 70%
...
When a duplicate Number is found, I would like to select the object with the lowest of the two percentages and feed those results to a new list.
source to share
Changing this based on the interpretation the "LINQ" poster wishes for query-query syntax instead of dot syntax (otherwise the rest of the answers would suffice):
var query =
from i in list
group i by i.Number into gj
select gj.OrderBy(x => x.Percentage).First();
But this still uses a lot of dot syntax for ordering. Which would be the functional equivalent:
var query =
from i in list
group i by i.Number into gj
select
(from i in gj
orderby i.Percentage
select i).First();
If you don't like the call .First()
at the end, it will be a problem that either has no solution within the framework of the LINQ language transformation, or the solution you end up with will not be the clean solution that IMHO Syntax provides this problem. Understanding queries can often make things easier, but in this case, I prefer the dot syntax:
var query =
list.GroupBy(i => i.Number)
.Select(gj => gj.OrderBy(i => i.Percentage).First());
Part gj.OrderBy(...).First()
performs More-LINQ style MinBy operation (see Jon Skeet's post )
source to share