tags:

views:

189

answers:

2

I have two ICollections 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
A: 

LINQ's IEnumerable.Union will work:

Mark Brackett
Less of the 'I'.
Paul Ruane
+2  A: 

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

Reed Copsey
Good call on the ToList()
Rosarch