gpt4 book ai didi

c# - GroupBy一个属性,把重复的做一个列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:42 26 4
gpt4 key购买 nike

我有一个包含一些记录的列表,其中一些具有相同的记录 ID。我想按该记录 ID 进行分组,并将其余属性设置为列表和一些字符串。这是我希望创建的对象:

public class Product {
public string Id{ get; set; }
public List<string> Package { get; set; }
public string ShortDescription { get; set; }
}

我要处理的记录是这样的:

list_Of_Records = [ { id: 123, Package: ABC, ShortDescription: Description },
{ id: 123, Package: ZXY, ShortDescription: Description },
{ id: 123, Package: MLO, ShortDescription: Description },
{ id: 456, Package: ABC, ShortDescription: DescriptionTwo },
{ id: 456, Package: ZXY, ShortDescription: DescriptionTwo },
{ id: 456, Package: MLO, ShortDescription: DescriptionTwo },
]

我想看起来像这样:

list_Of_Records_Organized = [
{ Id: 123, Package: [ABC, ZXY, MLO], ShortDescription: Description },
{ Id: 456, Package: [ABC, ZXY, MLO], ShortDescription: DescriptionTwo }
]

每个 ID 的描述始终相同,因此我可以选择三个中的任何一个。问题是那些包!

希望我说得足够清楚。

最佳答案

尝试这样的事情:

var list_Of_Records_Organized =
from r in list_Of_Records
group r by r.Id into g
select new Product {
Id = g.Key,
Package = g.Select(r => r.Package).ToList(),
ShortDescription = g.First().ShortDescription
};

或者在 Lambda 语法中:

var list_Of_Records_Organized = list_Of_Records.GroupBy(
r => r.Id,
(k, g) => new Product {
Id = k,
Package = g.Select(r => r.Package).ToList(),
ShortDescription = g.First().ShortDescription
});

关于c# - GroupBy一个属性,把重复的做一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834346/

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