How to add a range of items to an IList?

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

    If you look at the C# source code for List, I think List.AddRange() has optimizations that a simple loop doesn't address. So, an extension method should simply check to see if the IList is a List, and if so use its native AddRange().

    Poking around the source code, you see the .NET folks do similar things in their own LINQ extensions for things like .ToList() (if it is a list, cast it... otherwise create it).

    public static class IListExtension
    {
        public static void AddRange(this IList list, IEnumerable items)
        {
            if (list == null) throw new ArgumentNullException(nameof(list));
            if (items == null) throw new ArgumentNullException(nameof(items));
    
            if (list is List asList)
            {
                asList.AddRange(items);
            }
            else
            {
                foreach (var item in items)
                {
                    list.Add(item);
                }
            }
        }
    }
    

提交回复
热议问题