Reputation: 91
I have 2 dictionaries the first one has a key that are match multiple duplicate values in the second one:
var firstDic = new Dictionary<string, string>();
firstDic.Add("123", "Value1");
firstDic.Add("456", "Value2");
firstDic.Add("789", "Value3");
firstDic.Add("000", "Value4");
var secondDic = new Dictionary<string, string>();
secondDic.Add("5d866ac0-abab-46c9-a951-e7b0cf25dc72", "123");
secondDic.Add("217ddba3-977f-45b8-a7f6-80c6fbcef16e", "123");
secondDic.Add("99867f65-22c1-4b6c-b1bb-3fa73af317a9", "456");
secondDic.Add("203f9cf7-98f8-40fc-a4ba-da3a62c7d795", "456");
secondDic.Add("9bdafb4c-4d5a-4c87-8b9d-d9b98473390a", "789");
secondDic.Add("d3a245f0-cc5b-4c08-aaff-475d64e27e8d", "000");
I have a foreach in which i`m iterating over every key in the first dictionary
foreach (var item in firstDic)
{
//It`s only taking the first match in the secondDic
var myKey = secondDic.FirstOrDefault(x => x.Value == item.Key);
}
Is it possible to extract all the keys from the second dictionary(secondDic)that has the values matching from the first dictionary key and store them in some data structure.
Tnx in advice!
Upvotes: 1
Views: 104
Reputation: 32481
This may help
var result = secondDic.Where(s => firstDic.Any(f => f.Key == s.Value))
.Select(s => s.Key)
.ToList();
Upvotes: 0
Reputation: 62488
Then you don't need to use FirstOrDefault()
, just use the Where()
which will return a collection back :
var myKeys = secondDic.Where(x => x.Value == item.Key);
and then you can iterate over it:
foreach(var item in myKeys)
{
}
or do whatever business logic needs to be applied.
Upvotes: 1