Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Combining two generic lists

Tags:

Let's say I have two generic lists of the same type. How do I combine them into one generic list of that type?

like image 382
JamesBrownIsDead Avatar asked Jan 04 '10 22:01

JamesBrownIsDead


2 Answers

This should do the trick

List<Type> list1; List<Type> list2;  List<Type> combined; combined.AddRange(list1); combined.AddRange(list2); 
like image 157
Timo Willemsen Avatar answered Oct 03 '22 18:10

Timo Willemsen


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); 
like image 31
Guffa Avatar answered Oct 03 '22 17:10

Guffa