How to Merge Two Lists in C#: Simple Methods Explained
To merge two lists in C#, you can use the
AddRange method to add all elements from one list to another, or use LINQ's Concat method to create a new combined list. Both ways combine the elements, but AddRange modifies the original list while Concat returns a new list.Syntax
Here are two common ways to merge lists in C#:
- AddRange: Adds all elements from one list to the end of another list.
- Concat: Creates a new sequence by joining two lists without changing the originals.
csharp
list1.AddRange(list2);
var mergedList = list1.Concat(list2).ToList();Example
This example shows how to merge two lists using both AddRange and Concat. It prints the merged lists to the console.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> list1 = new List<int> { 1, 2, 3 }; List<int> list2 = new List<int> { 4, 5, 6 }; // Using AddRange (modifies list1) List<int> list1Copy = new List<int>(list1); // copy to keep original list1Copy.AddRange(list2); Console.WriteLine("Merged with AddRange:"); foreach (var item in list1Copy) { Console.Write(item + " "); } Console.WriteLine(); // Using Concat (creates new list) var mergedList = list1.Concat(list2).ToList(); Console.WriteLine("Merged with Concat:"); foreach (var item in mergedList) { Console.Write(item + " "); } Console.WriteLine(); } }
Output
Merged with AddRange:
1 2 3 4 5 6
Merged with Concat:
1 2 3 4 5 6
Common Pitfalls
Modifying original lists unintentionally: Using AddRange changes the first list, which might not be what you want if you need to keep it unchanged.
Forgetting to convert after Concat: Concat returns an IEnumerable, so you must call ToList() to get a list.
csharp
List<int> list1 = new List<int> { 1, 2 }; List<int> list2 = new List<int> { 3, 4 }; // Wrong: This changes list1 permanently list1.AddRange(list2); // Right: Create a new merged list without changing originals var merged = list1.Concat(list2).ToList();
Quick Reference
- AddRange: Use to add all elements from one list into another. Modifies the original list.
- Concat + ToList: Use to create a new merged list without changing originals.
- Remember to
using System.Linq;for LINQ methods likeConcat.
Key Takeaways
Use AddRange to merge lists when you want to modify the first list.
Use Concat with ToList to merge lists without changing the originals.
Always call ToList after Concat to get a List instead of IEnumerable.
Be careful not to unintentionally change your original lists.
Include System.Linq namespace to use LINQ methods like Concat.