2

I'll take inspiration from this previous question. I have a dictionary with lists inside, and I want to get the key by a value inside one of those.

Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
{
    {"1", new List<string>{"1a", "1b"} },
    {"2", new List<string>{"2a", "2b"} },
    {"3", new List<string>{"3a", "3b"} },
};

I'm confident that all values inside are unique.

I want something like this:

getByValueKey(string value);

getByValueKey("2a") must be return "2".

man-teiv
  • 419
  • 3
  • 16
  • 1
    I think you'll either have to iterate through all the entries to find it, or use this dictionary to build the reverse mapping dictionary and use that. Which is pretty much the same as the question you've linked, except you could test the values with .Contains("2a") not == "2a" – Rup Apr 23 '20 at 14:32
  • 1
    Thanks! I was wondering if there was a one-line solution similar to the one Kimi posted: `var myKey = types.FirstOrDefault(x => x.Value == "one").Key;` – man-teiv Apr 23 '20 at 14:35

2 Answers2

4

if you want to use linq, you could write:

var result = myDict.FirstOrDefault(p => p.Value.Contains(stringTofind)).Key;
Frenchy
  • 16,386
  • 3
  • 16
  • 39
2

I like Frenchy's answer, but if you're looking for a non-linqy solution, then:

Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
{
    {"1", new List<string>{"1a", "1b"} },
    {"2", new List<string>{"2a", "2b"} },
    {"3", new List<string>{"3a", "3b"} },
};

string stringToFind = "2a";

string matchingKey = null;
foreach(KeyValuePair<string, List<string>> kvp in myDict)
{
    if (kvp.Value.Contains(stringToFind))
    {
        matchingKey = kvp.Key;
        break;
    }
}

if (matchingKey != null)
{
    System.Console.WriteLine("Matching Key: " + matchingKey);
}
else
{
    System.Console.WriteLine("No match found.");
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • 1
    Thank you! Although I prefer Frenchy version (brevity is a pet peeve of mine) yours works perfectly. Much appreciated! – man-teiv Apr 23 '20 at 16:33