Reputation: 4715
Let's say I have two generic lists of the same type. How do I combine them into one generic list of that type?
Upvotes: 25
Views: 31706
Reputation: 832
If you're using C# 3.0/.Net 3.5:
List<SomeType> list1;
List<SomeType> list2;
var list = list1.Concat(list2).ToList();
Upvotes: 9
Reputation: 700800
You can simply add the items from one list to the other:
list1.AddRange(list2);
If you want to keep the lists and create a new one:
List<T> combined = new List<T>(list1);
combined.AddRange(list2);
Or using LINQ methods:
List<T> combined = list1.Concat(list2).ToList();
You can get a bit better performance by creating a list with the correct capacity before adding the items to it:
List<T> combined = new List<T>(list1.Count + list2.Count);
combined.AddRange(list1);
combined.AddRange(list2);
Upvotes: 20
Reputation: 16468
Using the .AddRange() method
http://msdn.microsoft.com/en-us/library/z883w3dc.aspx
Upvotes: 0
Reputation: 8857
This should do the trick
List<Type> list1;
List<Type> list2;
List<Type> combined;
combined.AddRange(list1);
combined.AddRange(list2);
Upvotes: 35