C# Linq:分组并从集合中选择
我有一门课:C# Linq:分组并从集合中选择,c#,linq,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 HexCo
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
我想获得LevelInfo Grouped的新集合不完全是这样,不知道如何正确地用HexColor表示。
对于上述数据,我希望获得包含3条记录的以下集合:
Id HexColor Caption MinPrice
1 color1 name1 10
3 color2 name3 10
4 color3 name3 10
我们不选择Id为2的记录,因为我们有Id为1的color1,它有最小价格。
我该怎么做?
谢谢。听起来你想分组,按MinPrice在组内订购,然后从每个组中选择第一个元素,对吗?如果这是正确的,您需要:
var query = from level in levels
group level by level.HexColor into levels
select levels.OrderBy(level => level.MinPrice).First();
或者,如果使用,您可以避免按MinPrice进行完整排序,只需选择具有最低价格的值:
var query = from level in levels
group level by level.HexColor into levels
select levels.MinBy(level => level.MinPrice);
听起来你想分组,按MinPrice在组内下单,然后从每个组中选择第一个元素,对吗?如果这是正确的,您需要:
var query = from level in levels
group level by level.HexColor into levels
select levels.OrderBy(level => level.MinPrice).First();
或者,如果使用,您可以避免按MinPrice进行完整排序,只需选择具有最低价格的值:
var query = from level in levels
group level by level.HexColor into levels
select levels.MinBy(level => level.MinPrice);