问题描述
说我有,相同类型的每个包含对象(例如,名单,LT集合任意数量; INT>富
和列表< INT>酒吧
)。如果这些藏品是他们自己的集合(例如,键入列表与LT的;列表< INT>>
,我可以使用的SelectMany
将它们全部组合成一个集合。
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo
and List<int> bar
). If these collections were themselves in a collection (e.g., of type List<List<int>>
, I could use SelectMany
to combine them all into one collection.
不过,如果这些集合尚未同一个集合中,这是我不得不写这样的方法我的IM pression:
However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:
public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
return toCombine.SelectMany(x => x);
}
这我然后调用是这样的:
Which I'd then call like this:
var combined = Combine(foo, bar);
有没有结合(任何数量的)的集合,而无需编写上述像的实用方法结合
一个干净,优雅的方式?它似乎很简单,应该有一个办法做到这一点的LINQ,但也许不是。
Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine
above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.
推荐答案
我想你可能会寻找LINQ的<$c$c>.Concat()$c$c>?
I think you might be looking for LINQ's .Concat()
?
var combined = foo.Concat(bar).Concat(foobar).Concat(...);
另外, .Union()
将删除重复的元素。
这篇关于优雅的方式来元素的多个集合结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!