Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Merge lists in C#
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
namespace test
{
class Person
{
public int Number { get; set; }
public string Name { get; set; }
}
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person p1, Person p2)
{
return p1.Number == p2.Number;
}
public int GetHashCode(Person p)
{
return p.Number;
}
}
class MainClass
{
public static void Main(string[] args)
{
var nameParts = new[] { "fe", "se", "ra", "ko", "il", "as", "os", "de", "ik" };
var rnd = new Random();
var list1 = Enumerable.Range( 0, 1000).Select(n => new Person() { Number = n, Name = RandomName(rnd, nameParts) }).ToList();
var list2 = Enumerable.Range(500, 1000).Select(n => new Person() { Number = n, Name = RandomName(rnd, nameParts) }).ToList();
var watch = new Stopwatch();
for (int _ = 0; _ < 5; _++)
{
Console.Write("Lists and LINQ merge: ");
watch.Restart();
for (int i = 0; i < 100; i++)
{
var merged = new List<Person>(list1);
merged.AddRange(list2.Where(p2 => list1.All(p1 => p1.Number != p2.Number)));
}
Console.WriteLine(watch.ElapsedMilliseconds + "ms");
Console.Write("Dictionary merge: ");
watch.Restart();
for (int i = 0; i < 100; i++)
{
var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
dict[person.Number] = person;
}
var merged = dict.Values.ToList();
}
Console.WriteLine(watch.ElapsedMilliseconds + "ms");
Console.Write("LINQ Union and IEqualityComparer: ");
watch.Restart();
for (int i = 0; i < 100; i++)
{
var merged = list1.Union(list2, new PersonComparer()).ToList();
}
Console.WriteLine(watch.ElapsedMilliseconds + "ms");
Console.Write("HashSet and IEqualityComparer: ");
watch.Restart();
for (int i = 0; i < 100; i++)
{
var hs = new HashSet<Person>(list1, new PersonComparer());
hs.UnionWith(list2);
var merged = hs.ToList();
}
Console.WriteLine(watch.ElapsedMilliseconds + "ms\n");
}
Console.ReadKey();
}
public static string RandomName(Random rnd, string[] nameParts)
{
return String.Join("", Enumerable.Range(0, 4).Select(_ => nameParts[rnd.Next(nameParts.Length)]).ToArray());
}
}
}
@jonelf

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.