當前位置:成語大全網 - 新華字典 - c#list<t>2個查找相同的合並

c#list<t>2個查找相同的合並

using System;

using System.Collections.Concurrent;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

List<A> list1 = Init(true);

List<A> list2 = Init(false);

var sw = Stopwatch.StartNew();

Dictionary<int, A> dic1 = list1.ToDictionary(m => m.id, m => m);

Dictionary<int, A> dic2 = list2.ToDictionary(m => m.id, m => m);

ConcurrentBag<A> results = new ConcurrentBag<A>();

Parallel.ForEach(dic1,

new ParallelOptions { MaxDegreeOfParallelism = 4 },

item =>

{

results.Add(new A { id = item.Key, name = item.Value.name, level = dic2[item.Key].level });

});

sw.Stop();

Console.WriteLine("用時:{0}毫秒", sw.ElapsedMilliseconds.ToString());

List<A> list3 = results.OrderBy(m => m.id).ToList();

for (int i = 0; i < 10; i++)

{

Console.WriteLine($"id:{list3[i].id} name:{list3[i].name} level:{list3[i].level}");

}

Console.ReadKey();

}

private static List<A> Init(bool isFirstList)

{

List<A> list = new List<A>();

for (int i = 0; i < 1000000; i++)

{

if (isFirstList)

list.Add(new A { id = i, name = $"name_{i.ToString()}" });

else

list.Add(new A { id = i, level = $"level_{i.ToString()}" });

}

return list;

}

public class A

{

public int id { get; set; }

public string name { get; set; }

public string level { get; set; }

}

}

}

不到壹秒,希望采納。。。。