Is there an easy way to append one IList<MyType> to another?
There's no great built-in way to do this. Really what you want is an AddRange
method but it doesn't exist on the IList<T>
(or it's hierarchy). Defining a new extension method though for this is straight forward
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> enumerable) {
foreach (var cur in enumerable) {
collection.Add(cur);
}
}
myList2.AddRange(myList1);
If you declare both list types as the concrete List
instead of IList
, you can use the AddRange
method:
List<MyType> myList1=new List<MyType>();
List<MyType> myList2=new List<MyType>();
myList2.AddRange(myList1);
otherwise you could use LINQ to combine the two:
using System.Linq;
IList<MyType> myList1=new List<MyType>();
IList<MyType> myList2=new List<MyType>();
var newList = myList1.Concat(myList2);
Use Enumerablr extension,
myList2=new List<MyType>(myList2.Concat(myList1))
BTW, if you do not populate myList2, you can just create it based on myLis1.
EDIT
I've try to research perfomance for several cases
1) AddRange via Add
List2.AddRange(List1);
public static class AddRangeUtils
{
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> enumerable)
{
foreach (var cur in enumerable)
{
collection.Add(cur);
}
}
}
2) Concat
List2 = new List<TestClass>(List2.Concat(List1))
3) Predefined Collection Count 1
var thirdList = new List<TestClass>(List2.Count + List1.Count);
foreach (var testClass in List1)
{
thirdList.Add(testClass);
}
foreach (var testClass in List2)
{
thirdList.Add(testClass);
}
List2 = thirdList;
4) Predefined Collection Count 2
var thirdList = new List<TestClass>(List2.Count + List1.Count);
thirdList.AddRange(List1);
thirdList.AddRange(List2);
List2 = thirdList;
Collection's Count is the count of elements for each list, List1 and List2: And came to such results (with different collection's length)