如何使用具有相同键的两个不同字典的值来构建新字典

时间:2016-09-06 14:30:13

标签: c# dictionary indexoutofrangeexception

假设我们有两个带有以下密钥对值的字典:

  • 字典1:[{1,abc} {2,cde} {3,efg}]
  • 字典2:[{1,123} {2,234} {3,345}]
  • 我想创建一个字典,如下所示: 字典3:[{abc,123} {cde,234} {efg,345}]

    removeHobby(index: number){
    (<FormArray>this.myForm.find('hobbies')).removeAt(index);
    }
    

我尝试了上述内容,但是我在

处获得了超出范围异常的索引

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)); } } } Error msg displayed in Console

2 个答案:

答案 0 :(得分:8)

只要查看您的示例词典,我就会建议:

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]);

但是看一下相当长的代码示例,我不确定它是否足够。

答案 1 :(得分:1)

试试这样:

var dictionaryC = dictionaryA.ToDictionary(dicA => dicA.Value, dicA => dictionaryB[dicA.Key]);