AddRange to a Collection

A coworker asked me today how to add a range to a collection. He has a class that inherits from Collection<T> . There's a get-only property of that type that already contains some items. He wants to add the items in another collection to the property collection. How can he do so in a C#3-friendly fashion? (Note the constraint about the get-only property, which prevents solutions like doing Union and reassigning.)

Sure, a foreach with Property. Add will work. But a List<T> -style AddRange would be far more elegant.

It's easy enough to write an extension method:

public static class CollectionHelpers
{
    public static void AddRange<T>(this ICollection<T> destination,
                                   IEnumerable<T> source)
    {
        foreach (T item in source)
        {
            destination.Add(item);
        }
    }
}

But I have the feeling I'm reinventing the wheel. I didn't find anything similar in System.Linq or morelinq.

Bad design? Just Call Add? Missing the obvious?


No, this seems perfectly reasonable. There is a List<T>. AddRange() method that basically does just this, but requires your collection to be a concrete List<T> .


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);
        }
    }
}

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.

链接地址: http://www.djcxy.com/p/9128.html

上一篇: 比继承更喜欢构图?

下一篇: AddRange添加到集合