当你的才华不能撑起你的野心时,就是你该选择学习的时候了!

List和Dictionary互转

// 声明Dictionary并初始化
            Dictionary<string, string> dic = new Dictionary<string, string>() { 
                {"1", "one"},
                {"2", "two"},
                {"3", "three"}
            };
            // 获得KeyList
            List<string> keyList = dic.Keys.ToList();

            // 获得ValueList
            List<string> valueList = dic.Values.ToList();
            
            // 获得KeyValuePairList
            List<KeyValuePair<string, string>> kvList = dic.ToList();
            
            // KeyValuePairList -> Dictionary
            Dictionary<string, string> dic2 = kvList.ToDictionary(item => item.Key, item => item.Value);

            // 在KeyValuePairList中添加一个重复Key,转换为Dictionary时异常
            kvList.Add(new KeyValuePair<string, string>("1", "1"));
            Dictionary<string, string> dic3 = kvList.ToDictionary(item => item.Key, item => item.Value);    // 发生异常
View Code

 

posted @ 2019-09-24 14:44  hofmann  阅读(2736)  评论(0编辑  收藏  举报