C#: Union of two ICollections? (equivalent of Java's addAll())

c#, coding-style, syntax

Solution

You can use the Enumerable.Union extension method:

result = result.Union(fromSubTree).ToList();

Since `result` is declared `ICollection<T>`, you'll need the `ToList()` call to convert the resulting `IEnumerable<T>` into a `List<T>` (which implements `ICollection<T>`). If enumeration is acceptable, you could leave the `ToList()` call off, and get deferred execution (if desired).

Problem

I have two `ICollection`s of which I would like to take the union. Currently, I'm doing this with a foreach loop, but that feels verbose and hideous. What is the C# equivalent of Java's `addAll()`? Example of this problem: ``` ICollection<IDictionary<string, string>> result = new HashSet<IDictionary<string, string>>(); // ... ICollection<IDictionary<string, string>> fromSubTree = GetAllTypeWithin(elementName, element); foreach( IDictionary<string, string> dict in fromSubTree ) { // hacky result.Add(dict); } // result is now the union of the two sets ```

Original source