C# 多个个Dictionary合并更优雅的写法


Dictionary

现在有两个Dictionary的对象,想把两个对象的中数据合并成一个。

使用for循环的话觉得非常不合适,于是考虑是否有相应的方法,网上找了很多,都是for循环,最后终于找到了一个,参考:http://jworkmail.blog.163.com/blog/static/201049108201402134027951/

Dictionary<int, int> a = new Dictionary<int, int>();
a.Add(3, 3);

Dictionary<int, int> b = new Dictionary<int, int>();
b.Add(4, 6);

a=a.Concat(b).ToDictionary(k => k.Key, v => v.Value);

最后得到的a就是a与b的合并的所有元素。

横斩:

List合并(参考:http://www.cnblogs.com/liguanghui/archive/2011/11/09/2242309.html)

 List<int> listA = new List<int> {1,2,3,5,7,9};
 List<int> listB = new List<int> {13,4,17,29,2};
 
 listA.AddRange(listB );把集合A.B合并
 List<int> Result = listA.Union(listB).ToList<int>();          //剔除重复项 
 List<int> Result = listA.Concat(listB).ToList<int>();        //保留重复项

还有其他类型的合并,暂不列出。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM