2016-09-20 43 views
0

我有一個字典列表,如:C#從列表創建字典<Dictionary>

dic1.Add("A_key1","A_val11"); dic1.Add("B_key1","B_val11") 
dic1.Add("C","C"); dic1.Add("D","D"); 

dic2.Add("A_key1","A_val21"); dic1.Add("B_key1","B_val21"); 
dic2.Add("C","C"); dic1.Add("D","D"); 
dic2.Add("A_key2","A_val22"); dic1.Add("B_key2","B_val22"); 
dic2.Add("A_key3","A_val23"); dic1.Add("B_key3","B_val23"); 

List<Dictionary<string,string>> tempList = new List<Dictionary<string,string>>{dic1, dic2}; 

我需要從tempList創建字典遵循的規則:關鍵= 「A_Key的*」 值,VAL =「B_key * 「來自列表中所有原始字典的價值。 例如,在上例中:

expectDic = {("A_val11","B_val11"), 
       ("A_val21","A_val21"), 
       ("A_val22","A_val22"), 
       ("A_val23","A_val23")} 

我可以用Linq解決嗎?

+1

'SelectMany'和'ToDictionary'的組合可能會訣竅 –

+0

是否會只有2個字典?那麼這兩個字典中沒有匹配鍵的項目呢? – sachin

+0

什麼是'dic2'? – Maarten

回答

0

你的問題還不清楚,所以我打算做一些假設。如果這些假設不正確,請讓我知道並適當修改。

因爲關鍵字是相同的,所以合併這些字典將不可能,因此列表中的數據不會出現在您的測試數據中。

最後,您的測試數據本身不正確,因爲它會引發異常。因此,我所做的測試數據爲如下的假設:

 Dictionary<string, string> dic1 = new Dictionary<string, string>(); 
     Dictionary<string, string> dic2 = new Dictionary<string, string>(); 

     dic1.Add("A_1", "A_val11"); 
     dic1.Add("B_1", "B_val11"); 
     dic1.Add("C", "C"); 
     dic1.Add("D", "D"); 


     dic2.Add("A_1", "A_val21"); 
     dic2.Add("A_2", "A_val22"); 
     dic2.Add("A_3", "A_val23"); 
     dic2.Add("B_1", "B_val21"); 
     dic2.Add("B_2", "B_val22"); 
     dic2.Add("B_3", "B_val23"); 
     dic2.Add("C", "C"); 
     dic2.Add("D", "D"); 


     List<Dictionary<string, string>> tempList = new List<Dictionary<string, string>> { dic1, dic2 }; 

下面是一些代碼,這將對於給出的示例工作:

Dictionary<string, string> expectDic = new Dictionary<string, string>(); 
     for (int i = 0; i < tempList.Count; i++) 
     { 
      Dictionary<string, string> onedic = tempList[i]; 
      while (onedic.Values.ToList().Where(x => x.Contains("A_")).FirstOrDefault() != null) 
      { 
       expectDic.Add(onedic.Select(x => x.Value).Where(x => x.Contains("A_") && !expectDic.Keys.Contains(x)).First(), onedic.Select(x => x.Value).Where(x => x.Contains("B_") && !expectDic.Values.Contains(x)).First()); 
       onedic.Remove(onedic.Select(x => x.Key).Where(x => x.Contains("A_")).FirstOrDefault()); 
       onedic.Remove(onedic.Select(x => x.Key).Where(x => x.Contains("B_")).FirstOrDefault()); 
      } 
     } 

但是,你問的是非常複雜的我會推薦LINQ的異常處理。