比较两个字典 c# 并获得相同的键
Compare two dictionaries c# and get the same keys
我有两本词典。一个是实际的字典(键的词和值的定义),另一个是 Word 文件中的词,存储在第二本词典中。
//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]);
但它不起作用。
有谁可以帮助我吗,
谢谢你。 (抱歉我的英文不是很好)
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);
我有两本词典。一个是实际的字典(键的词和值的定义),另一个是 Word 文件中的词,存储在第二本词典中。
//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]);
但它不起作用。
有谁可以帮助我吗,
谢谢你。 (抱歉我的英文不是很好)
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);