问题
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 });
回答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());
回答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.
来源:https://stackoverflow.com/questions/13644078/return-min-value-in-group-with-lambda-linq-query