简体   繁体   中英

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?

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)

计算结果

我使用了一种方法:

Array.ForEach(ilist1.ToArray(), x => ilist2.Add(x));

If the run-time type of the second list is List<T> , you can cast to that type and use the AddRange() method.

Otherwise, you have to do it yourself with a loop. Alternatively, you could use linq to create a new list containing the contents of both source lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM