gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:41 24 4
gpt4 key购买 nike

我有一个类:

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);

关于c# - Linq:分组并从集合中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11175662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com