C#
.NET
merge lists
programming
coding tips

Merge two or more lists into one, in C .NET

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Overview

In C# .NET, merging two or more lists into one is a common operation, especially when working with collections. This operation can be performed using various techniques, depending on the use case and the specific functionalities you desire in the merged list. The most common list structure in C# is the List<T>, a generic collection offered by the .NET framework. This article will delve into several methods to merge lists in C#, providing code examples and a technical discussion on the advantages of each approach.

Basic Concepts

Before embarking on list merging, let's recall some fundamentals about the List<T> in C#:

  • Generic type: The List<T> is a part of System.Collections.Generic, and it can hold elements of any data type.
  • Dynamic resizing: Unlike arrays, lists are dynamically resizable, meaning they can grow or shrink as needed.

Methods to Merge Lists

Using AddRange

One of the simplest methods to merge two lists is by using the AddRange method. This method appends the elements of one list to the end of another.

Code Example:

csharp
1using System;
2using System.Collections.Generic;
3
4class MergeListsExample
5{
6    static void Main()
7    {
8        List<int> list1 = new List<int> { 1, 2, 3 };
9        List<int> list2 = new List<int> { 4, 5, 6 };
10
11        list1.AddRange(list2);
12
13        foreach (int number in list1)
14        {
15            Console.WriteLine(number);
16        }
17    }
18}

In this example, list2 is appended to list1, resulting in a single list containing elements &#123;1, 2, 3, 4, 5, 6&#125;.

Using LINQ's Concat

The Concat method available in LINQ can be used to merge lists in an elegant and functional style. It creates a concatenated sequence of elements from the lists.

Code Example:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class MergeListsLinqExample
6{
7    static void Main()
8    {
9        List<string> list1 = new List<string> { "apple", "banana" };
10        List<string> list2 = new List<string> { "orange", "grape" };
11
12        IEnumerable<string> mergedList = list1.Concat(list2);
13
14        foreach (string fruit in mergedList)
15        {
16            Console.WriteLine(fruit);
17        }
18    }
19}

The result of this operation is a merged enumerable containing all elements from both lists.

Using the Union Method

If you want to merge lists while removing duplicates, LINQ's Union method provides an efficient way. It combines two sequences and excludes duplicates.

Code Example:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class MergeListsUnionExample
6{
7    static void Main()
8    {
9        List<int> list1 = new List<int> { 1, 2, 3, 4 };
10        List<int> list2 = new List<int> { 3, 4, 5, 6 };
11
12        IEnumerable<int> mergedList = list1.Union(list2);
13
14        foreach (int number in mergedList)
15        {
16            Console.WriteLine(number);
17        }
18    }
19}

Here, the resulting list will be &#123;1, 2, 3, 4, 5, 6&#125; without repeated elements.

Using a Custom Merge Function

For more complex merging rules, you may need to implement a custom merging function. This approach provides the flexibility to define precise merging logic based on specific criteria.

Code Example:

csharp
1using System;
2using System.Collections.Generic;
3
4class CustomMergeExample
5{
6    static void Main()
7    {
8        List<Customer> list1 = new List<Customer> 
9        {
10            new Customer { Id = 1, Name = "John" },
11            new Customer { Id = 2, Name = "Jane" }
12        };
13        List<Customer> list2 = new List<Customer> 
14        {
15            new Customer { Id = 1, Name = "Johnny" },
16            new Customer { Id = 3, Name = "Janet" }
17        };
18
19        List<Customer> mergedList = CustomMerge(list1, list2);
20        foreach (var customer in mergedList)
21        {
22            Console.WriteLine($"{customer.Id} - {customer.Name}");
23        }
24    }
25
26    static List<Customer> CustomMerge(List<Customer> list1, List<Customer> list2)
27    {
28        Dictionary<int, Customer> customerDict = new Dictionary<int, Customer>();
29        
30        foreach (var customer in list1)
31        {
32            if (!customerDict.ContainsKey(customer.Id))
33                customerDict[customer.Id] = customer;
34        }
35        
36        foreach (var customer in list2)
37        {
38            if (!customerDict.ContainsKey(customer.Id))
39                customerDict[customer.Id] = customer;
40        }
41
42        return new List<Customer>(customerDict.Values);
43    }
44}
45
46class Customer
47{
48    public int Id { get; set; }
49    public string Name { get; set; }
50}

In this example, the custom merging function uses a dictionary to keep track of customers by their ID, effectively merging the lists and ensuring no duplicate IDs.

Summary Table

TechniqueKey CharacteristicsUse Case
AddRangeSimple, appends one list to anotherWhen order is important and duplicates are allowed
LINQ ConcatReturns a concatenated enumerableFunctional style without altering original lists
LINQ UnionCombines sequences, removes duplicatesWhen order is not critical and duplicates must be removed
Custom FunctionUser-defined logic, often involves complex scenariosCustom merging rules and deduplication based on specific criteria

Conclusion

Merging two or more lists in C# .NET can be accomplished in several ways, each with specific pros and cons. For simple applications, built-in methods like AddRange and LINQ's Concat are quick and efficient. When preventing duplicates, the Union method is useful. For custom scenarios, implementing a custom merge logic provides the necessary control over the process. Understanding these techniques enables developers to manage collections effectively, improving code maintainability and performance.


Course illustration
Course illustration

All Rights Reserved.