+ 1
How do I get the key of that value from a dictionary with a value?
4 ответов
+ 2
Well dictionary's are not designed to do that, so this is the other way around. But it is not impossible. You can do it using a for each loop.
Have a look at the code below.
https://code.sololearn.com/c01sV8ggP6YR/?ref=app
+ 6
Using foreach loop as Sneeze suggested works! I had tried it in this code
https://code.sololearn.com/cpTJu66yK1DM/?ref=app
+ 3
Harold SKRT🤘🤘🤘 I'm just now realizing I might have been a bit presumptuous in assuming you were asking how to retrieve the dictionary key from within a foreach loop. I responded at around 5am my time and was quite tired in that moment. 😉
Upon... revisiting your exact question and seeing the response from sneeze, I now believe you might be asking how to retrieve keys that hold a certain value.
That is to say, using the sample dictionary I previously posted, for a given value, "Doe" for example, you want to retrieve the associated key name "LastName".
Let me know if this is the context of your question and I'll follow up with additional clarifications. 😉👌
+ 2
Harold SKRT🤘🤘🤘
I think this is what you're looking for.
----
var dict = new Dictionary<string, string>(){
{"FirstName", "John"},
{"LastName", "Doe"},
{"City", "Atlanta"},
{"State", "Georgia"},
{"Country", "USA"}
};
foreach(var (key, value) in dict){
WriteLine(quot;{key} => {value}");
}
----
Note: You can use WriteLine(...) as I have it above if you include the following line in your code:
using static System.Console;