gpt4 book ai didi

c# - LINQ 查询返回每个类别中价格最高的项目

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

这是对我不久前发布的一个问题的跟进。我得到了答案,但我意识到我已经将我的示例类简化到了失去初衷的地步。已经接受了对原始问题的回答后,我认为最好开始另一个问题。

所以,这是我的新类(class):

public class Art
{
public string Type { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}

...这是列表创建:

public static void Example0000()
{
List<Art> art = new List<Art>();
art.Add(new Art() { Price = 45, Type = "painting", Name = "Still Life in Maryland" });
art.Add(new Art() { Price = 123, Type = "sculpture", Name = "Dying Sheep" });
art.Add(new Art() { Price = 12, Type = "icon", Name = "Perplexed Smiley" });
art.Add(new Art() { Price = 460, Type = "sculpture", Name = "Waves on Sand" });
art.Add(new Art() { Price = 2030, Type = "painting", Name = "Robert in the Morning" });
art.Add(new Art() { Price = 10, Type = "icon", Name = "Smiley Picking Nose" });
art.Add(new Art() { Price = 700, Type = "painting", Name = "Birds in Autumn" });
art.Add(new Art() { Price = 1400, Type = "sculpture", Name = "Holding Hands" });
art.Add(new Art() { Price = 46, Type = "painting", Name = "Reeling Him In" });
art.Add(new Art() { Price = 12000, Type = "sculpture", Name = "Old Dog" });
art.Add(new Art() { Price = 6, Type = "icon", Name = "Hiding Smiley" });
art.Add(new Art() { Price = 810, Type = "sculpture", Name = "Rhinestone Cowgirl" });
art.Add(new Art() { Price = 250, Type = "painting", Name = "Upstairs, Downstairs" });
art.Add(new Art() { Price = 3, Type = "icon", Name = "Dopey Smiley" });
art.Add(new Art() { Price = 1000, Type = "painting", Name = "Young Love" });
art.Add(new Art() { Price = 260, Type = "sculpture", Name = "Taking a Spill" });
}

我要获取的是一个对象的集合,每个Type对应一个,具有三个属性;艺术类型、艺术名称和最昂贵的价格。对于每种类型,我需要该类型中价格最高的商品的名称和价格。

所以我的列表应该是这样的:

绘画______Robert_in_the_Morning______2030

雕塑_____老狗__________________12000

图标_________困惑的笑脸______________12

为此,LINQ 会是什么样子?我开始的示例如下所示:

var categories4 =
from a in art
group a by a.Type into g
let maxPrice = g.Max(p => p.Price)
select new { ArtType = g.Key, MostExpensive = g.Where(a => a.Price == maxPrice) };

最佳答案

这对你有用吗?

var query =
art
.OrderByDescending(x => x.Price)
.GroupBy(x => x.Type)
.Select(x => x.First());

我得到这个结果:

Query Result

关于c# - LINQ 查询返回每个类别中价格最高的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372606/

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