2017-06-19 111 views
0

我有兩個字典。一個是實際的詞典(詞的鍵和定義的價值),另一個是在Word文件中存儲在第二字典中的單詞。比較兩個字典c#並獲得相同的密鑰

//first dictionary 
    var xdoc = XDocument.Load("dicoFrancais.xml"); 
      var dico = xdoc.Root.Elements() 
           .ToDictionary(a => (string)a.Attribute("nom"), 
              a => (string)a.Element("DEFINITION")); 

//second dictionary 
Dictionary<string, string> motRap = new Dictionary<string, string>(); 
     Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); 
     Document document = application.Documents.Open("monfichiertxt.docx"); 


     int count = document.Words.Count; 
     for (int i = 1; i <= count; i++) 
     {     
      string text = document.Words[i].Text;     
      motRap.Add(text, "blabla");     
     } 
     // Close word. 
     application.Quit(); 

我想比較兩個庫的鑰匙,並獲得與第一字典的值相同的密鑰,所以有我了,第三次字典與鍵和值。 我試過這個: var intersectMembers = dico.Keys.Intersect(motRap.Keys) .ToDictionary(t => t, t => dico[t]); 但它不起作用。 有人可以幫我, 謝謝。 (對不起,我的英文不太好)

+1

「但它不起作用」是什麼意思?你得到了什麼結果,你期望什麼? – HimBromBeere

+0

第三個字典沒有顯示 – titi2fois

回答

0

我想比較兩個字典的鍵值,並得到與第一個字典的值相同的鍵。

var thirdDictionary = dico 
    .Where(keyValue => motRap.Keys.Contains(keyValue.Key)) 
    .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value); 
相關問題