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
You can also do this without doing an expensive sort on each group:
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.