3

I have a dictionary where the key is string and the value is a list of strings.

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>() {
    {"alpha", new List<string> {"one", "two", "three"}}
    {"beta", new List<string> {"four", "five", "six"}}
    {"gamma", new List<string> {"seven", "eight", "nine"}}
}

Is there a way to return the key when given a string that exist in the value?

For example, given "four", return "beta"

I found something like this, but it works only when the value is single and not a list, and I don't know how I can do this with a list.

Thanks.

Community
  • 1
  • 1
sora0419
  • 2,308
  • 9
  • 39
  • 58

2 Answers2

3

Searching a dictionary by value is not efficient, however:

string firstKey = dict.Where(kv => kv.Value.Contains("four"))
    .Select(kv => kv.Key)
    .FirstOrDefault(); // returns null if no list contains "four"

or you could provide a default key if no list contains a given value, then it's safe to use First:

string firstKey = dict.Where(kv => kv.Value.Contains("foo"))
    .Select(kv => kv.Key)
    .DefaultIfEmpty("--no value found--")
    .First(); // result: "--no value found--"
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

The problem here is there could be multiple keys for any given string value. Hence you would need to return a collection versus a single key. This could be done as follows

IEnumerable<string> FindAllKeys(Dictionary<string, List<string>> map, string value) {
  foreach (var pair in map) {
    if (pair.Value.IndexOf(value) >= 0) {
      yield return pair.Key;
    }
  }
}

If you wanted to cut this search off at the first match you could just employ the FirstOrDefault extension method

FindAllKeys(dict, "four").FirstOrDefault();
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454