将范围添加到集合 [英] AddRange to a Collection
问题描述
今天一位同事问我如何将范围添加到集合中.他有一个继承自 Collection
的类.有一个该类型的 get-only 属性已经包含一些项目.他想将另一个集合中的项目添加到属性集合中.他怎么能以 C#3 友好的方式做到这一点?(请注意关于 get-only 属性的约束,这会阻止诸如联合和重新分配之类的解决方案.)
A coworker asked me today how to add a range to a collection. He has a class that inherits from Collection<T>
. There's a get-only property of that type that already contains some items. He wants to add the items in another collection to the property collection. How can he do so in a C#3-friendly fashion? (Note the constraint about the get-only property, which prevents solutions like doing Union and reassigning.)
当然,一个带有属性的 foreach.添加将起作用.但是 List
样式的 AddRange 会优雅得多.
Sure, a foreach with Property. Add will work. But a List<T>
-style AddRange would be far more elegant.
编写扩展方法很容易:
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 中没有找到类似的内容.
But I have the feeling I'm reinventing the wheel. I didn't find anything similar in System.Linq
or morelinq.
糟糕的设计?只是调用添加?缺少明显的东西?
Bad design? Just Call Add? Missing the obvious?
推荐答案
不,这似乎完全合理.有一个 List
方法基本上就是这样做的,但要求你的集合是一个具体的 List
.
No, this seems perfectly reasonable. There is a List<T>.AddRange()
method that basically does just this, but requires your collection to be a concrete List<T>
.
这篇关于将范围添加到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!