tags:

views:

55

answers:

1

Is there some method in ICollection in C# that would add all elements of another collection? Right now I have to always write foreach cycle for this:

ICollection<Letter> allLetters = ... //some initalization
ICollection<Letter> justWrittenLetters = ... //some initalization
... //some code, adding to elements to those ICollections

foreach(Letter newLetter in justWrittenLetters){
    allLetters.add(newLetter);
}

My question is, is there method that can replace that cycle? Like for example the method addAll(Collection c) in Java ? So I would write only something like:

allLetters.addAll(justWrittenLetters);
+7  A: 

There isn't a method like this for ICollection. You have two options, either use a different type such as List which has the AddRange() method or alternatively, create an extension method:

public static class CollectionExtensions
{
    public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> newItems)
    {
        foreach (T item in newItems)
        {
            collection.Add(item);
        }
    }
}
s1mm0t