Linq:分组并从集合中进行选择

时间:2012-06-24 07:16:18

标签: c# linq

我有一个班级:

public class LevelInfo
    {
        public int Id { get; set; }
        public string HexColor { get; set; }
        public string Caption { get; set; }
        public int MinPrice { get; set; }
    }

我有一个LevelInfo的集合。例如,我们有以下数据:

Id     HexColor     Caption     MinPrice
1       color1       name1         10
2       color2       name2         20
3       color2       name3         10
4       color3       name4         10

我想通过HexColor获得LevelInfo的新集合(不完全,不知道如何正确说明)。 对于上面的数据,我想获得包含3条记录的以下集合:

Id     HexColor     Caption     MinPrice
1       color1       name1         10
3       color2       name3         10
4       color3       name3         10

我们不选择Id等于2的记录,因为我们有color1Id = 1)并且它有最低价格。 我怎样才能做到这一点? 感谢。

1 个答案:

答案 0 :(得分:4)

所以听起来你想要分组,通过MinPrice在组中订购,然后从每个组中选择第一个元素,对吗?如果这是正确的,你想要:

var query = from level in levels
            group level by level.HexColor into levels
            select levels.OrderBy(level => level.MinPrice).First();

或者,如果您使用MoreLINQ,则可以避免MinPrice完成排序,只需选择最低价格的值:

var query = from level in levels
            group level by level.HexColor into levels
            select levels.MinBy(level => level.MinPrice);