C# 中的 ICollection 中是否有一些方法可以添加另一个集合的所有元素? 现在我必须始终为此编写 foreach 循环:
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);
}
我的问题是,有没有方法可以替代那个循环?例如方法 addAll(Collection c)
在 java ?所以我只会写这样的东西:
allLetters.addAll(justWrittenLetters);
最佳答案
ICollection 没有这样的方法。您有两个选择,要么使用不同的类型,例如具有 AddRange() 方法的 List,要么创建一个扩展方法:
public static class CollectionExtensions
{
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> newItems)
{
foreach (T item in newItems)
{
collection.Add(item);
}
}
}
关于c# - C# ICollection 中的方法,将另一个 ICollection 的所有元素添加到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2984624/