gpt4 book ai didi

C# 林奇 : Get items with max price

转载 作者:太空狗 更新时间:2023-10-29 20:50:46 25 4
gpt4 key购买 nike

我有一个对象列表:

class MyObj
{
public String Title { get; set; }
public Decimal Price { get; set; }
public String OtherData { get; set; }
}

var list = new List<MyObj> {
new MyObj { Title = "AAA", Price = 20, OtherData = "Z1" },
new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "BBB", Price = 10, OtherData = "Z10" },
new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" }
};

获取具有唯一标题和 MAX(价格)列表的最佳方法是什么。结果列表需要:

var ret = new List<MyObj> {
new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" }
};

最佳答案

好吧,你可以这样做:

var query = list.GroupBy(x => x.Title)
.Select(group =>
{
decimal maxPrice = group.Max(x => x.Price);
return group.Where(x => x.Price == maxPrice)
.First();
};

如果您需要 LINQ to SQL(其中您不能使用语句 lambda),您可以使用:

var query = list.GroupBy(x => x.Title)
.Select(group => group.Where(x => x.Price == group.Max(y => y.Price))
.First());

请注意,在 LINQ to Objects 中,Where 的每次迭代效率较低,它将重新计算最高价格。

如果您希望能够返回多个具有给定名称且价格相同的商品,请调整 .First() 部分。

在 LINQ to Objects 中,您还可以使用 MoreLINQMaxBy方法:

var query = list.GroupBy(x => x.Title)
.Select(group => group.MaxBy(x => x.Price));

关于C# 林奇 : Get items with max price,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6123472/

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