AddRange to a Collection

后端 未结 8 2153
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 11:41

A coworker asked me today how to add a range to a collection. He has a class that inherits from Collection. There\'s a get-only property of that type t

相关标签:
8条回答
  • 2020-12-01 12:24

    Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.

    public static void AddRange<T>(this ICollection<T> destination,
                                   IEnumerable<T> source)
    {
        List<T> list = destination as List<T>;
    
        if (list != null)
        {
            list.AddRange(source);
        }
        else
        {
            foreach (T item in source)
            {
                destination.Add(item);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 12:26

    Remember that each Add will check the capacity of the collection and resize it whenever necessary (slower). With AddRange, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.

    0 讨论(0)
提交回复
热议问题