要的AddRange集合 [英] AddRange to a Collection
问题描述
一个同事问我今天怎么一个范围内添加到集合。他有一个从继承收藏℃的类; T>
。有一个得到只已经包含一些项目该类型的物业。他想在另一个集合中添加项目到属性集合。他怎么能在C#3友好的方式做到这一点?的(注意有关Get-唯一的财产,以防止像做联盟和重新分配方案的约束。)的
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。添加会工作。但列表< T>
风格的AddRange将更为优雅。
Sure, a foreach with Property. Add will work. But a List<T>
-style AddRange would be far more elegant.
这是很容易编写扩展。方法:
It's easy enough to write an extension method:
public static class CollectionHelpers
{
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
但我有感觉,我M重新发明轮子。我没有发现类似的事情在 System.Linq的
或 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屋!