0

我知道我可以Linq用来生成 2 个IEnumerable集合的并集。

它应该是这样的:

IEnumerable<MyClass> first;
IEnumerable<MyClass> second; 
IEnumerable<MyClass> union = first.Union(second);

现在假设我有一个班级的集合IEnumerable,我想计算所有班级的并集。对优雅(并且可能有效)的方式有什么建议吗?

我试过这样的东西,但这不是正确的语法:

IEnumerable<IEnumerable<MyClass>> collection;
IEnumerable<MyClass> result = Enumerable.Empty<MyClass>().Union( foreach (MyClass c in collection ){ yield return c;});
4

2 回答 2

3
collection.SelectMany(i => i).Distinct(); //will get your result.
于 2013-06-10T14:34:40.417 回答
3

O(n) 中的以下方法,而不是使用AggregateO(n²) 的方法。

collection.SelectMany(i => i).Distinct()
于 2013-06-10T14:36:42.603 回答