Return min value in group with lambda/linq query

10,781

Solution 1

Using Linq,

First Group using Enumerable.GroupBy
Then Sort using Enumerable.OrderBy
Then Take First of each sorted items in group

    radios.GroupBy(x=> x.Channel).Select(x=>x.OrderBy(y=>y.Price)).Select(x=>x.First());

Solution 2

You can also do this without doing an expensive sort on each group:

radios.GroupBy(x => x.Channel).Select(g =>
    g.Aggregate((r1, r2) => r1.Price < r2.Price ? r1 : r2));

The Aggregate iterates through each group once, keeping track of the cheapest radio it's found so far and replacing it if it finds a cheaper one.

Share:
10,781
mstrand
Author by

mstrand

Updated on June 04, 2022

Comments

  • mstrand
    mstrand almost 2 years

    I need help creating a lambda expression to query the following list for retrieving the lowest priced item in each channel. Ie for this example item A, D and G

    class Radio
    {
        public string Name { get; set; }
        public int Channel { get; set; }
        public decimal Price { get; set; }
    }
    
    List<Radio> radios = new List<Radio>();
    radios.Add(new Radio() { Name = "A", Channel = 1, Price = 10 });
    radios.Add(new Radio() { Name = "B", Channel = 1, Price = 20 });
    radios.Add(new Radio() { Name = "C", Channel = 1, Price = 30 });
    radios.Add(new Radio() { Name = "D", Channel = 2, Price = 10 });
    radios.Add(new Radio() { Name = "E", Channel = 2, Price = 20 });
    radios.Add(new Radio() { Name = "F", Channel = 2, Price = 30 });
    radios.Add(new Radio() { Name = "G", Channel = 3, Price = 10 });
    radios.Add(new Radio() { Name = "H", Channel = 3, Price = 20 });
    radios.Add(new Radio() { Name = "I", Channel = 3, Price = 30 });
    
    • smoothumut
      smoothumut almost 6 years
      great question. same with my problem that is wonferfully defined