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.

+3


source to share


5 answers


Try to run

var list = originalList
    .GroupBy(x => x.Number)
    .Select(x => x.OrderBy(y => y.Percentage).First())
    .ToList();

      



This query will first group the items by value Number

. It then orders each group by percentage and selects the first item (which is the lowest).

+4


source


var query = from x in list
            group x by x.Number into x
            select x.OrderBy(y => y.Percentage).First();

      



+4


source


Will this work?

collection.GroupBy(item => item.Number).Select(group => group.Min())

      

+3


source


  var query = (from l in lst
         group l by l.Number into g
         select g.Min(x => x.Percentage)).ToList();

      

+1


source


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 )

+1


source







All Articles