tags:

views:

497

answers:

4

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

+5  A: 

This should do the trick

List<Type> list1;
List<Type> list2;

List<Type> combined;
combined.AddRange(list1);
combined.AddRange(list2);
Timo Willemsen
Is this the most efficient, or the most convenient way?
Hamish Grubijan
pstst .AddRange, Java is over there ->
blu
@Ipthnc, I dont know a other way to do it, other than a `foreach()` combined with `List.Add()`. But it sure is the most convenient way.
Timo Willemsen
@gah. Heh im programming java right now. Annoying naming conventions.
Timo Willemsen
Why not just do list1.AddRange(list2)? It meets the requirements without having to create an additional list, and saves an entire add.
Erich
@Erich, that sure is a better way. My example just demonstrated the use.
Timo Willemsen
Err, *no*, that's not necessarily a better way. You're assuming that it's OK to modify the first list (for that matter, why not do it to the second list instead?) when that's not made clear.
Adam Robinson
Indeed, that's the assumtion me and Erich made. I have to adjust my opinion on that one. Assuming it is okay to modify the first list, it is faster.
Timo Willemsen
+1  A: 

Using the .AddRange() method

http://msdn.microsoft.com/en-us/library/z883w3dc.aspx

Computer Linguist
+3  A: 

If you're using C# 3.0/.Net 3.5:

List<SomeType> list1;
List<SomeType> list2;

var list = list1.Concat(list2).ToList();
Rafa Castaneda
As a clarification, this requires .NET 3.5, not just C# 3.0 (extension methods are a part of C# 3.0, but the `System.Linq.Enumerable` class that defines them is part of .NET 3.5)
Adam Robinson
@Adam Robinson: Thanks for the precision.
Rafa Castaneda
This can work on .NET 2.0 if you use VS2008 and LinqBridge ;)
Thomas Levesque
+4  A: 

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);
Guffa