I am having trouble getting the key by specifying a value. What is the best way I can achieve this?
var st1= new List<string> { "NY", "CT", "ME" };
var st2= new List<string> { "KY", "TN", "SC" };
var st3= new List<string> { "TX", "OK", "MO" };
var statesToEmailDictionary = new Dictionary<string, List<string>>();
statesToEmailDictionary.Add("[email protected]", st1);
statesToEmailDictionary.Add("[email protected]", st2);
statesToEmailDictionary.Add("[email protected]", st3);
var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Where(y => y.Contains(state))).Key;
var emailAdd = statesToEmailDictionary.First(x=>x.Value.Contains(state)).Key;
The return value from FirstOrDefault
will be a KeyValuePair<string, List<string>>
, so to get the key, simply use the Key
property. Like this:
var emailAdd = statesToEmailDictionary
.FirstOrDefault(x => x.Value.Contains(state))
.Key;
Alternatively, here's the equivalent in query syntax:
var emailAdd =
(from p in statesToEmailDictionary
where p.Value.Contains(state)
select p.Key)
.FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With