How to add a range of items to an IList?

后端 未结 5 626
忘了有多久
忘了有多久 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:26

    You could also write an extension method like this:

    internal static class EnumerableHelpers
    {
        public static void AddRange(this IList collection, IEnumerable items)
        {
            foreach (var item in items)
            {
                collection.Add(item);
            }
        }
    }
    

    Usage:

    IList collection = new MyCustomList(); //Or any other IList except for a fixed-size collection like an array
    var items = new[] {1, 4, 5, 6, 7};
    collection.AddRange(items);
    

    Which is still iterating over items, but you don't have to write the iteration or cast every time you call it.

提交回复
热议问题