How to add a range of items to an IList?

后端 未结 5 623
忘了有多久
忘了有多久 2021-02-04 23:23

There is no AddRange() method for IList.

How can I add a list of items to an IList without iterating through the

5条回答
  •  北海茫月
    2021-02-04 23:30

    AddRange is defined on List, not the interface.

    You can declare the variable as List instead of IList or cast it to List in order to gain access to AddRange.

    ((List)myIList).AddRange(anotherList);
    

    This is not good practice (see comments below), as an IList might not be a List, but some other type that implemented the interface and may very well not have an AddRange method - in such a case, you will only find out when your code throws an exception at runtime.

    So, unless you know for certain that the type is indeed a List, you shouldn't try to use AddRange.

    One way to do so is by testing the type with the is or as operators (since C# 7).

    if(myIList is List)
    {
       // can cast and AddRange
    }
    else
    {
       // iterate with Add
    }
    

提交回复
热议问题