Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method in ICollection in C# that adds all elements of another ICollection to it

Tags:

c#

collections

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);
like image 955
Rasto Avatar asked Jun 06 '10 14:06

Rasto


1 Answers

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);
        }
    }
}
like image 195
s1mm0t Avatar answered Oct 02 '22 14:10

s1mm0t