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);
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With