2015-07-20 56 views
-1

我有2時listItems如何合併2時listItems

  1. 首先

    {Id = 1, Name = "a"}{Id = 2, Name = "b"}{Id = 3, Name = "c"} 
    
  2. {Id = 2, Name = "b"}{Id = 3, Name = "c"}{Id = 4, Name = "d"} 
    

如何將它們合併,並得到一個列表項,如:

{Id = 1, Name = "a"}{Id = 2, Name = "b"}{Id = 3, Name = "c"}{Id = 4, Name = "d"} 

回答

0

是這樣的嗎?

class items { 
      public int id; 
      public string name; 
      } 

static void Main(string[] args) 
     { 
      var list = new List<items>(); 
      list.Add(new items {id=1 , name="a"}); 
      list.Add(new items { id = 2, name = "b" }); 
      list.Add(new items { id = 3, name = "c" }); 

      var list1 = new List<items>(); 
      list1.Add(new items { id = 2, name = "b" }); 
      list1.Add(new items { id = 3, name = "c" }); 
      list1.Add(new items { id = 4, name = "d" }); 

      var c = list.Select(b=> new {b.id, b.name}); 
      var d = list1.Select(b => new { b.id, b.name }); 
      var merge = c.Concat(d).Distinct().ToList(); 

      foreach (var item in merge) 
      { 
       Console.WriteLine(item); 
      } 

      Console.ReadKey(); 
    } 
0
var list1 = new[]{new {Id = 1, Name = "a"},new {Id = 2, Name = "b"}, new{Id = 3, Name = "c"}}.ToList(); 
var list2 = new[]{new {Id = 1, Name = "a"},new {Id = 2, Name = "b"}, new{Id = 3, Name = "c"}}.ToList(); 

list1.AddRange(list2); 

然後list1是合併的列表。

0

您可以使用 「的AddRange」 或 「聯盟」 或C# 「的毗連」 功能

var list1 = new[]{new {Id = 1, Name = "a"},new {Id = 2, Name = "b"}, new{Id = 3, Name = "c"}}.ToList(); 

var list2 = new[]{new {Id = 1, Name = "a"},new {Id = 2, Name = "b"}, new{Id = 3, Name = "c"}}.ToList(); 

然後

var MergedResult = list1.Union(list2).ToList(); 

var MergedResult = list1.AddRange(list2).ToList(); 

你也可以使用Concat。 ...

查看它們之間的區別.NET List Concat vs AddRange