Let's say I have two generic lists of the same type. How do I combine them into one generic list of that type?
This should do the trick
List<Type> list1; List<Type> list2; List<Type> combined; combined.AddRange(list1); combined.AddRange(list2);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With