如何在C#中与列表相交? [英] How to intersect list in c#?
本文介绍了如何在C#中与列表相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在c#中具有以下 Item 对象的列表:
I have following list of Item objects in c#:
public class Item
{
public int Id { get; set; }
public List<string> Orders { get; set; }
}
List<Item> item = new List<Item>() {
new Item() { Id = 1, Code = 23, Orders = new List<string>() { "A", "B" }},
new Item() { Id = 2, Code = 24, Orders = new List<string>() { "C", "D" }},
new Item() { Id = 1, Code = 23, Orders = new List<string>() { "E", "F" }},
new Item() { Id = 3, Code = 25, Orders = new List<string>() { "G", "H" }}
};
我要合并ID相同的订单,因此上面列表的输出应为:
I want to concat the Orders whose Id is same, so the output of above list should be:
{
new Item() { Id = 1, Code = 23, Orders = new List<string>() { 'A', 'B', 'E', 'F' },
new Item() { Id = 2, Code = 24, Orders = new List<string>() { 'C', 'D' },
new Item() { Id = 3, Code = 25, Orders = new List<string>() { 'G', 'H' }
};
我如何才能在c#中有效地做到这一点(如果可能,请使用linq)?
How can i do this efficiently in c# ( using linq if possible ) ?
推荐答案
您要根据项目的ID对项目进行分组,然后根据该组的所有Orders
创建新序列.
You want to group the items based on their ID, and then create a new sequences based on all of the Orders
for that group.
var query = items.GroupBy(item => item.Id)
.Select(group => new Item
{
Id = group.Key,
Orders = group.SelectMany(item => item.Orders).ToList()
});
请注意,这不是任何数据的交集.您将获得每个组中所有数据的 union .
Note that this is not the intersection of any data. You're getting the union of all data within each group.
这篇关于如何在C#中与列表相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文