如何合并两个不同的列表

时间:2019-03-05 06:21:07

标签: c#

我有一个List<string> list1,示例值:

var list1 = new List<string>()
{
    "123", "1234", "12345",
};

我有一堂课

public class TestClass {
    public string name{ get; set; }
    public int count{ get; set; }
}

我有一个List<TestClass> list2的示例值:

var list2 = new List<TestClass>()
{
    new TestClass() { name = "12", count = 0 },
    new TestClass() { name = "123", count = 5 },
    new TestClass() { name = "1234", count = 20 },
};

我要合并list1list2,结果应该是:

name        count
12          0
123         5
1234        20
12345       0

3 个答案:

答案 0 :(得分:6)

这很好用:

var list1 = new List<string>()
{
    "123", "1234", "12345",
};

var list2 = new List<TestClass>()
{
    new TestClass() { name = "12", count = 0 },
    new TestClass() { name = "123", count = 5 },
    new TestClass() { name = "1234", count = 20 },
};

var merged =
    list2
        .Concat(list1.Select(x => new TestClass() { name = x, count = 0 }))
        .GroupBy(x => x.name)
        .SelectMany(x => x.Take(1))
        .ToList();

它给了我

merged

答案 1 :(得分:0)

您可以尝试将linq selectunion一起使用。

然后通过GroupBy属性使用name,然后使用sum

var aaa= list1.Select(x => new TestClass()
{
    name = x.ToString(),
    count = 0
}).Union(list2)
    .GroupBy(x=>x.name)
    .Select(x=>new TestClass()
{
    name = x.Key,
    count = x.Sum(z=>z.count)
});

答案 2 :(得分:0)

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        List<TestClass> lst1 = new List<TestClass>();
        lst1.Add(new TestClass(){name="One", count = 1});
        lst1.Add(new TestClass(){name="Two", count = 2});
        lst1.Add(new TestClass(){name="Three", count = 3});

        List<TestClass> lst2 = new List<TestClass>();
        lst2.Add(new TestClass(){name="Four", count = 4});
        lst2.Add(new TestClass(){name="Two", count = 2});
        lst2.Add(new TestClass(){name="Three", count = 3});

        var unionlst = lst1.Union(lst2, new TestClassComparer ());

        foreach(var x in unionlst){
            Console.WriteLine(x.name + ","+x.count);
        }
    }

    class TestClassComparer : IEqualityComparer<TestClass>
    { 
        public bool Equals(TestClass p1, TestClass p2)
        {
            return p1.name == p2.name && p1.count == p2.count;
        }

        public int GetHashCode(TestClass p)
        {
            return p.count;
        }
    }

    public class TestClass {
        public string name{ get; set; }
        public int count{ get; set; }
    }
}

示例输出:

1,1

2,2

3,3

4,4