最佳答案
今天一个同事问我如何向一个集合添加一个范围。他有一个从 Collection<T>
继承的类。该类型的 get-only 属性已经包含一些项。他希望将另一个集合中的项添加到属性集合中。他怎么能以 C # 3友好的方式做到这一点呢?(请注意关于 get-only 属性的约束,它阻止执行 Union 和重新分配等解决方案。)
当然,使用 Property. Add 的 foreach 可以工作,但是使用 List<T>
风格的 AddRange 会更加优雅。
写一个扩展方法很简单:
public static class CollectionHelpers
{
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
但是我有一种重造轮子的感觉,在 System.Linq
和 Morelinq中我没有发现任何类似的东西。
糟糕的设计? 只是调用添加? 忽略了显而易见的东西?