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

69,430

Solution 1

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

Solution 2

What everyone in this thread failed to mention is that the FirstOrDefault method is only available through Linq:

using System;
using System.Collections.Generic;
// FirstOrDefault is part of the Linq API
using System.Linq;

namespace Foo {
    class Program {
        static void main (string [] args) {
            var d = new Dictionary<string, string> () {
                { "one", "first" },
                { "two", "second" },
                { "three", "third" }
            };
            Console.WriteLine (d.FirstOrDefault (x => x.Value == "second").Key);
        }
    }
}

Solution 3

I think you want:

var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Any(y => y.Contains(state))).Key;

Solution 4

var emailAdd = statesToEmailDictionary.First(x=>x.Value.Contains(state)).Key;

Solution 5

var emailAdd = statesToEmailDictionary
    .FirstOrDefault(x => x.Value != null && x.Value.Contains(state))
    .Key;

But if you're looking for performance, I'd suggest reversing your dictionary and creating a dictionary of <state, email> to do what you're looking for.

// To handle when it's not in the results
string emailAdd2 = null;
foreach (var kvp in statesToEmailDictionary)
{
    if (kvp.Value != null && kvp.Value.Contains(state))
    {
        emailAdd2 = kvp.Key;
        break;
    }
}
Share:
69,430
Krishh
Author by

Krishh

Updated on April 28, 2020

Comments

  • Krishh
    Krishh about 4 years

    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;