Skip to main content
 首页 » 编程设计

c#之Linq:分组并从集合中选择

2024年02月20日30lvdongjie

我有一个类:

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 的记录,因为我们有 color1(Id =1)并且它有最低价格。 我怎样才能做到这一点? 谢谢。

请您参考如下方法:

听起来您想要分组,按 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);