Why doesn't IList support AddRange

后端 未结 2 1029
余生分开走
余生分开走 2020-12-09 00:54

List.AddRange() exists, but IList.AddRange() doesn\'t.
This strikes me as odd. What\'s the reason behind this?

2条回答
  •  悲&欢浪女
    2020-12-09 01:01

    For those who want to have extension methods for "AddRange", "Sort", ... on IList,

    Below is the AddRange extension method:

     public static void AddRange(this IList source, IEnumerable newList)
     {
         if (source == null)
         {
            throw new ArgumentNullException(nameof(source));
         }
    
         if (newList == null)
         {
            throw new ArgumentNullException(nameof(newList));
         }
    
         if (source is List concreteList)
         {
            concreteList.AddRange(newList);
            return;
         }
    
         foreach (var element in newList)
         {
            source.Add(element);
         }
    }
    

    I created a small library that does this. I find it more practical than having to redo its extension methods on each project.

    Some methods are slower than List but they do the job.

    Here is the GitHub to interest them:

    IListExtension repository

提交回复
热议问题