13

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
Aubin
  • 14,617
  • 9
  • 61
  • 84
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699

3 Answers3

14

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
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    Unfortunately, the union works as if the origin and the destiny were sets, and it overlooks repeated elements, therefore this is not the same as doing and Java `Collection.addAll()` where the collection implementation may well be a List, where repeated elements are valid. – Edwin Dalorzo May 30 '12 at 22:41
  • 2
    @edalorzo In this case, you can use Enumerable.Concat instead: http://msdn.microsoft.com/en-us/library/bb302894 – Reed Copsey May 30 '12 at 22:51
9

AddRange() appends the source list to the end of another, and may suit your needs.

destList.AddRange(srcList);
ubzack
  • 1,878
  • 16
  • 16
-1

LINQ's Enumerable.Union will work:

James McMahon
  • 48,506
  • 64
  • 207
  • 283
Mark Brackett
  • 84,552
  • 17
  • 108
  • 152