9

我需要帮助创建一个 lambda 表达式来查询以下列表,以检索每个渠道中价格最低的商品。即对于本示例项目 A、D 和 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 });
4

2 回答 2

18

使用 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());
于 2012-11-30T11:21:37.523 回答
14

您也可以这样做,而无需对每个组进行昂贵的排序:

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

遍历每个Aggregate组一次,跟踪迄今为止找到的最便宜的收音机,如果找到更便宜的收音机,则更换它。

于 2012-11-30T11:57:48.980 回答