Dictionary: Get key instead of value

Lep255

Member
Joined
Apr 3, 2022
Messages
7
Programming Experience
Beginner
I'm currently using this code:
C#:
static class CharRanks
        {
            static Dictionary<string, string> Ranks = new Dictionary<string, string>
            {
                {"51", "Maj. Gen"},
                {"52", "Lt. Gen"},
                {"53", "General"},
                {"54", "Admiral"}
            };

            public static string GetRanks(string Ranking)
            {
                // Get the result from the Ranks Dictionary.
                string RankResult;
                if (Ranks.TryGetValue(Ranking, out RankResult))
                {
                    return RankResult;
                }
                else
                {
                    return null;
                }
            }
        }
And then I'm calling as such: _CharLvl.SelectedItem = CharRanks.GetRanks($"{CharLevelID}");


Rather than making a whole new Dictionary with {"Name","Numer"}, I'd like to know how I can get the Value to return the Key.
 
C#:
foreach(var keyValuePair in Ranks)
{
    if (keyValuePair.Value == Ranking)
        return keyValuePair.Key;
}
return null;

OR

C#:
return Ranks.FirstOrDefault(kvp => kvp.Value == Ranking)?.Key;
 
Back
Top Bottom