AddRange to a Collection

后端 未结 8 2155
伪装坚强ぢ
伪装坚强ぢ 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(this ICollection destination,
                                   IEnumerable source)
    {
        List list = destination as List;
    
        if (list != null)
        {
            list.AddRange(source);
        }
        else
        {
            foreach (T item in source)
            {
                destination.Add(item);
            }
        }
    }
    

提交回复
热议问题