C#:两个ICollection的并集?(相当于Java的addAll())
我有两个I集合s,我想取其中的一个。目前,我正在使用foreach循环进行此操作,但这感觉冗长而可怕。Java的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
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和JavaCollection.addAll()
不同,在Java和Java中,集合实现可能是一个列表,重复的元素是有效的。@edalorzo在这种情况下,您可以使用Enumerable.Concat代替: