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?
ICollection<T>
does not seem to have anAdd
method. msdn.microsoft.com/en-us/library/… HoweverCollection<T>
has one. – Tim GoodmanAdd(T item)
in the first place? Seems like a half-baked approach to offer the ability to add a single item and then expect all callers to iterate in order to add more than one at a time. Your statement is certainly true forIEnumerable<T>
but I have found myself frustrated withICollections
on more than one occasion. I don't disagree with you, just venting. – akousmata