如何从C#中的不同列表合并2个对象? [英] How to merge 2 object from different list in c#?
问题描述
我在c#中有以下两个 Item 对象列表:
I have following 2 list of Item objects in c#:
public class Item
{
public int Id { get; set; }
public List<string> Orders { get; set; }
}
List<Item> items1 = 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" }}
};
List<Item> items2 = new List<Item>() {
new Item() { Id = 1, Code = 23, Orders = new List<string>() { "E", "F" }},
new Item() { Id = 2, Code = 24, Orders = new List<string>() { "G", "H" }}
};
我想合并ID和代码相同的两个列表中的Item对象,因此以上两个列表的输出应为具有以下条目的单个列表:
I want to merge the Item objects from both lists whose Id and code is same, so the output of above 2 list should be single list with the following entries:
{
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', 'G', 'H' }
};
我如何使用linq在c#中做到这一点?
How can i do this in c# using linq ?
推荐答案
您可以同时加入两个列表,然后加入Union
他们的Orders
,例如:
You can join both list and then Union
their Orders
like:
List<Item> combined = (from t in items1
join r in items2 on new { t.Id, t.Code } equals new { r.Id, r.Code }
select new Item
{
Id = t.Id,
Code = t.Code,
Orders = t.Orders.Union(r.Orders).ToList()
}).ToList();
您将获得:
如果需要连接Orders
,则可以将Union
替换为Concat
.因此,如果您的订单包含"A","B"和"A","F",那么使用concat您将获得"A","B,"A","F"
,而使用Union
您将获得"A", "B", "F"
If you need your Orders
to be concatenated then you can replace Union
with Concat
. So if your order contains "A", "B" and "A", "F", then with concat you will get "A","B,"A","F"
and with Union
you will get "A", "B", "F"
这篇关于如何从C#中的不同列表合并2个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!