简体   繁体   English

比较两个字典C#并获得相同的键

[英]Compare two dictionaries c# and get the same keys

I have two Dictionaries. 我有两个字典。 One is an actual dictionary (word for key and definition for value) and the other is words that are in a Word File and stored in a seconde dictionary. 一个是实际的词典(关键字为键,值的定义),另一个为Word文件中并存储在seconde词典中的单词。

//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();

And I want to compare the keys of the two dictionaries and get the same keys with the values of the first dictionary, so i can have a third dictionary with that keys and values. 而且我想比较两个字典的键,并使用第一个字典的值获得相同的键,这样我就可以拥有带有该键和值的第三个字典。 i tried this : var intersectMembers = dico.Keys.Intersect(motRap.Keys) .ToDictionary(t => t, t => dico[t]); 我试过这个: var intersectMembers = dico.Keys.Intersect(motRap.Keys) .ToDictionary(t => t, t => dico[t]); but it doesn't work. 但这不起作用。 Can someone help me please, Thank you. 有人可以帮我吗,谢谢。 (Sorry my english is not very good) (对不起,我的英语不是很好)

I want to compare the keys of the two dictionaries and get the same keys with the values of the first dictionary. 我想比较两个字典的键,并获得与第一个字典的值相同的键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM