Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to append one IList<MyType> to another?

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?

like image 464
Michael Goldshteyn Avatar asked Mar 01 '12 16:03

Michael Goldshteyn


People also ask

Can you append one list to another?

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).

How do I append a list to another?

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.

How do you append a list to another list in Java?

Use addAll () method to concatenate the given list1 and list2 into the newly created list.

Is += list the same as append?

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.


1 Answers

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);
like image 77
JaredPar Avatar answered Sep 17 '22 12:09

JaredPar