Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 326
Nick Heiner Avatar asked Mar 17 '10 18:03

Nick Heiner


1 Answers

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

like image 97
Reed Copsey Avatar answered Oct 05 '22 23:10

Reed Copsey