简体   繁体   中英

Return min value in group with lambda/linq query

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 });

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());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM