将AddRange添加到集合 [英] AddRange to a Collection
问题描述
同事今天问我如何向集合添加范围。他有一个继承自 Collection< T>
的类。有一个已经包含一些项目的类型的只有属性。他想将另一个集合中的项目添加到属性集合。他怎么能这样做在C#3友好的时尚?
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.)
当然,这是一个有关Property的foreach。添加将工作。但是 List< T>
- 样式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?
推荐答案
不,这似乎是完全合理的。有一个列表< T>。
AddRange()方法,基本上只是这样,但要求您的集合是一个具体的列表< T>
。
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>
.
这篇关于将AddRange添加到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!