TrueWill TrueWill - 1 year ago 115
C# Question

AddRange to a Collection

A coworker asked me today how to add a range to a collection. He has a class that inherits from

. 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
-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)

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

Bad design? Just Call Add? Missing the obvious?

Answer Source

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>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download