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
2010-01-04 22:36:05
Is this the most efficient, or the most convenient way?
Hamish Grubijan
2010-01-04 22:37:38
pstst .AddRange, Java is over there ->
blu
2010-01-04 22:39:10
@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
2010-01-04 22:39:59
@gah. Heh im programming java right now. Annoying naming conventions.
Timo Willemsen
2010-01-04 22:40:51
Why not just do list1.AddRange(list2)? It meets the requirements without having to create an additional list, and saves an entire add.
Erich
2010-01-04 22:43:42
@Erich, that sure is a better way. My example just demonstrated the use.
Timo Willemsen
2010-01-04 22:45:22
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
2010-01-04 22:46:31
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
2010-01-04 22:50:10
+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
2010-01-04 22:40:06
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
2010-01-04 22:45:15
+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
2010-01-04 22:49:23