我有一个包含一些记录的列表,其中一些记录具有相同的记录ID。我希望按该记录ID进行分组,并将其余属性设置为Lists和一些字符串。这是我希望创建的对象:
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的描述总是相同的,所以我可以选择三个中的任何一个。问题是那些包裹!
希望我足够清楚。
答案 0 :(得分:3)
尝试这样的事情:
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
});
答案 1 :(得分:3)
organizedList = list_of_records
.GroupBy(m => m.id)
.Select(m => new {
Id = m.Key,
Package = m.SelectMany(x => x.Package).ToArray(),
ShortDescription = m.First().ShortDescription
});
但这意味着您将采用任意ShortDescription(每组中找到的第一个)。
顺便说一句,你的样本不清楚。
Package是字符串还是字符串列表?在您的课程中,它是List<string>
,但在您的示例中,它看起来像一个字符串。
如果是字符串,请在
中使用Select而不是SelectManyPackage = m.Select(x => x.Package).ToArray(),