如何在c#中合并来自不同列表的2个对象?

时间:2014-04-02 18:10:38

标签: c# linq

我在c#中有以下2个 Item 对象列表:

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对象,因此上面2列表的输出应该是单个列表,其中包含以下条目:

{ 
  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#中执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以加入这两个列表,然后Union加入Orders,例如:

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();

你会得到:

enter image description here

如果您需要将Orders连接起来,则可以将Union替换为Concat。因此,如果您的订单包含“A”,“B”和“A”,“F”,那么使用concat,您将获得"A","B,"A","F",而使用Union,您将获得"A", "B", "F"

答案 1 :(得分:1)

var result = from x in items1
             join y in items2 on x.Id equals y.Id
             select new Item
                {
                    Id = x.Id, 
                    Code = x.Code,
                    Orders = x.Orders.Concat(y.Orders).ToList()
                };