使用lambda / linq查询返回组中的最小值

时间:2012-11-30 11:10:55

标签: c# .net linq lambda linq-to-objects

我需要帮助创建一个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 });

2 个答案:

答案 0 :(得分:15)

使用Linq,

第一组使用Enumerable.GroupBy
然后使用Enumerable.OrderBy进行排序 然后获取组中每个已排序项目的First

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

答案 1 :(得分:11)

您也可以在不对每个组进行昂贵的排序的情况下执行此操作:

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

Aggregate遍历每个组一次,跟踪到目前为止发现的最便宜的无线电,如果找到更便宜的无线电,则替换它。