C#:两个ICollections的联盟?(相当于Java的addAll())

Nic*_*ner 12 c# syntax coding-style

我有两个ICollection我想参加工会的.目前,我正在使用foreach循环执行此操作,但这感觉冗长而丑陋.什么是Java的C#等价物addAll()

此问题的示例:

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
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 13

您可以使用Enumerable.Union扩展方法:

result = result.Union(fromSubTree).ToList();
Run Code Online (Sandbox Code Playgroud)

result声明以来ICollection<T>,您将需要ToList()调用将结果IEnumerable<T>转换为List<T>(实现ICollection<T>).如果枚举是可接受的,您可以ToList()关闭该调用,并获得延迟执行(如果需要).

  • @edalorzo在这种情况下,您可以使用Enumerable.Concat:http://msdn.microsoft.com/en-us/library/bb302894 (2认同)

ubz*_*ack 7

AddRange() 将源列表附加到另一个列表的末尾,可能适合您的需要.

destList.AddRange(srcList);
Run Code Online (Sandbox Code Playgroud)