加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:05:39 所属栏目:百科 来源:网络整理
导读:我有两个ICollections,我想拿这个工会.目前,我正在做一个foreach循环,但感觉到冗长和可怕.什么是 Java的addAll()的C#等价物? 这个问题的例子: ICollectionIDictionarystring,string result = new HashSetIDictionarystring,string();// ...ICollectionIDic
我有两个ICollections,我想拿这个工会.目前,我正在做一个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

解决方法

您可以使用 Enumerable.Union扩展方法:
result = result.Union(fromSubTree).ToList();

由于结果被声明为ICollection< T>,您将需要ToList()调用来转换所得到的IEnumerable< T>列入列表< T> (其实现ICollection< T>).如果枚举是可以接受的,您可以离开ToList()调用,并获得延迟执行(如果需要).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读