C#:两个ICollection的并集?(相当于Java的addAll())

C#:两个ICollection的并集?(相当于Java的addAll()),c#,syntax,coding-style,C#,Syntax,Coding Style,我有两个I集合s,我想取其中的一个。目前,我正在使用foreach循环进行此操作,但这感觉冗长而可怕。Java的addAll()的C#等价物是什么 此问题的示例: ICollection<IDictionary<string, string>> result = new HashSet<IDictionary<string, string>>(); // ... ICollection<IDictionary<string, strin

我有两个I集合s,我想取其中的一个。目前,我正在使用foreach循环进行此操作,但这感觉冗长而可怕。Java的
addAll()
的C#等价物是什么

此问题的示例:

ICollection<IDictionary<string, string>> result = new HashSet<IDictionary<string, string>>();
// ...
ICollection<IDictionary<string, string>> fromSubTree = GetAllTypeWithin(elementName, element);
foreach( IDictionary<string, string> dict in fromSubTree ) { // hacky
    result.Add(dict);
}
// result is now the union of the two sets
ICollection result=new HashSet();
// ...
ICollection fromSubTree=GetAllTypeWithin(elementName,element);
foreach(fromSubTree中的IDictionary dict){//hacky
结果:添加(dict);
}
//现在的结果是两个集合的并集
LINQ将起作用:

您可以使用扩展方法:

result = result.Union(fromSubTree).ToList();
由于
result
声明为
ICollection
,因此需要调用
ToList()
将结果
IEnumerable
转换为
列表(实现
ICollection
)。如果枚举是可接受的,您可以取消调用
ToList()
,并获得延迟执行(如果需要)。

将源列表附加到另一个列表的末尾,并且可能适合您的需要

destList.AddRange(srcList);

不幸的是,union的工作方式就像原点和命运被设置一样,它忽略了重复的元素,因此这与doing和Java
Collection.addAll()
不同,在Java和Java中,集合实现可能是一个列表,重复的元素是有效的。@edalorzo在这种情况下,您可以使用Enumerable.Concat代替: