Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key from value - Dictionary<string, List<string>>

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;
like image 784
Krishh Avatar asked May 31 '13 15:05

Krishh


2 Answers

var emailAdd = statesToEmailDictionary.First(x=>x.Value.Contains(state)).Key;
like image 191
G.J Avatar answered Oct 26 '22 02:10

G.J


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();
like image 35
p.s.w.g Avatar answered Oct 26 '22 02:10

p.s.w.g