how to do a dictionary reverse lookup

前端 未结 5 1542
悲哀的现实
悲哀的现实 2021-02-05 04:23

I have a dictionary of type and for a particular case, I need to do a reverse lookup. So for instance suppose I have this entry <\"S

5条回答
  •  面向向阳花
    2021-02-05 05:03

    Basically, You can use LINQ and get the Key like this, without reversing anything:

    var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key;
    

    If you really want to reverse your Dictionary, you can use an extension method like this:

    public static Dictionary Reverse(this IDictionary source)
    {
         var dictionary = new Dictionary();
         foreach (var entry in source)
         {
             if(!dictionary.ContainsKey(entry.Value))
                 dictionary.Add(entry.Value, entry.Key);
         }
         return dictionary;
    } 
    

    Then you can use it like this:

    var reversedDictionary = dictionary.Reverse();
    var key = reversedDictionary["ab"];
    

    Note: if you have duplicate values then this method will add the first Value and ignore the others.

提交回复
热议问题