Here is some sample code:
IList<MyType> myList1=new List<MyType>();
IList<MyType> myList2=new List<MyType>();
// Populate myList1
...
// Add contents of myList1 to myList2
myList2.Add(myList1); // Does not compile
How do I add the contents of one list to another - is there a method for this?
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
append() : append the element to the end of the list. insert() : inserts the element before the given index. extend() : extends the list by appending elements from the iterable. List Concatenation: We can use the + operator to concatenate multiple lists and create a new list.
Use addAll () method to concatenate the given list1 and list2 into the newly created list.
For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.
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 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