简体   繁体   中英

How to merge two different List

I have a List<string> list1 , example values:

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

I have a class:

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

and I have a List<TestClass> list2 , example values:

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

I want to merge list1 and list2 and the result should be:

name        count
12          0
123         5
1234        20
12345       0

This works nicely:

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

It gives me:

合并的

You can try to use linq select with union .

then use GroupBy by name property then 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)
});
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; }
    }
}

Sample output:

One,1

Two,2

Three,3

Four,4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM