如何合并2个列表项目

时间:2015-07-20 03:19:35

标签: c# merge listitem

我有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"}
    
  3. 如何合并它们并获得类似的列表项:

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

3 个答案:

答案 0 :(得分: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();
     }

答案 1 :(得分: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是合并列表。

答案 2 :(得分:0)

您可以使用&#34; AddRange&#34;或者&#34; Union&#34;或者&#34; Concat&#34; 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

中查看它们之间的区别