【发布时间】:2011-05-28 11:44:44
【问题描述】:
假设我有任意数量的集合,每个集合都包含相同类型的对象(例如,List<int> foo 和 List<int> bar)。如果这些集合本身在一个集合中(例如,List<List<int>> 类型,我可以使用 SelectMany 将它们全部组合到一个集合中。
但是,如果这些集合不在同一个集合中,我的印象是我必须编写这样的方法:
public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
return toCombine.SelectMany(x => x);
}
然后我会这样称呼:
var combined = Combine(foo, bar);
有没有一种简洁、优雅的方式来组合(任意数量的)集合,而不必编写像上面的 Combine 这样的实用方法?看起来很简单,在 LINQ 中应该有一种方法可以做到这一点,但也许没有。
【问题讨论】:
-
当心 Concat 连接大量可枚举,可能会炸毁你的堆栈:programmaticallyspeaking.com/…
标签: c# linq generics collections