如何使用来自两个具有相同键的不同字典的值构建一个新字典
本文关键字:字典 新字典 一个 构建 何使用 两个 | 更新日期: 2023-09-27 18:05:57
假设我们有两个字典,它们的键对值如下:
- 字典1:[{1,abc} {2, cde} {3, efg}]
- 字典2:[{1123}{2234}{3345}]
-
我想创建一个字典如下:字典3:[{abc,123} {cde,234} {efg,345}]
fieldValues = new List<List<string>>(); docFieldKey = new List<List<string>>(); docFieldValueDict = new Dictionary<string, List<string>>(); docKeyDict = new Dictionary<string, List<string>>(); iterateDocKeyDict = new List<string>(); iterateDocFldValueDict = new List<string>(); //To read row wise and store key and all values for (limit = 0; limit < docNames.Count; limit++) { for (row = 0; row < excelData.Count; row++) { if (excelData[row] == docNames[limit]) { for (colLimit = row + 1; colLimit < fieldNames.Count; colLimit++) { flag = true; fieldValues.Add(new List<string>()); fieldValues[limit].Add(excelData[colLimit]); } if (flag == true) { docFieldValueDict.Add(docNames[limit], fieldValues[limit]); } } } } //To add concatenated key for each docName for (limit = 0; limit < docNames.Count; limit++) { for (colLimit = 0; colLimit < concatKey.Count; colLimit++) { if (concatKey[colLimit].Contains(docNames[limit])) { for (col = colLimit; col < fieldNames.Count - 1; col++) { flag = true; docFieldKey.Add(new List<string>()); docFieldKey[limit].Add(concatKey[col]); } if (flag == true) { docKeyDict.Add(docNames[limit], docFieldKey[limit]); } } } } //to merge the key and the value from both dictionaries for (limit = 0; limit <docKeyDict.Count; limit++) { var docKeyDictCompare = docKeyDict.ElementAt(limit); var docFldValueDictCompare = docFieldValueDict.ElementAt(limit); iterateDocKeyDict = docKeyDictCompare.Value; iterateDocFldValueDict = docFldValueDictCompare.Value; if (docKeyDictCompare.Key == docFldValueDictCompare.Key) { for (col = 0; col < fieldNames.Count - 1; col++) { if ((iterateDocKeyDict.ElementAt(col)!=string.Empty) && (iterateDocFldValueDict.ElementAt(col)!=string.Empty)) { flag = true; } } if (flag == true) { keyValuePairDict.Add(iterateDocKeyDict.ElementAt(col), iterateDocFldValueDict.ElementAt(col)); } } }
我尝试了上面的操作,但是我在
处得到了index out of range异常 if ((iterateDocKeyDict.ElementAt(col)!=string.Empty) &&(iterateDocFldValueDict.ElementAt(col)!=string.Empty))
控制台
看看你的样本字典,我建议:
var dic1 = /* [ {1,abc} {2,cde} {3,efg} ] */;
var dic2 = /* [ {1,123} {2,234} {3,345} ] */;
var dic3 = dic1.ToDictionary(x => x.Value, x => dic2[x.Key]);
但是看看你相当长的代码示例,我不确定它是否足够。
试一下:
var dictionaryC = dictionaryA.ToDictionary(dicA => dicA.Value, dicA => dictionaryB[dicA.Key]);