Getting key of value of a generic Dictionary?

2018-12-31 15:08发布

It's easy to get the value of a key from a .Net 2.0 generic Dictionary:

Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2];  // Beta

But is there a simple way to get the key of a value?

int[] betaKeys = greek.WhatDoIPutHere("Beta");  // expecting single 2

标签: c# .net
14条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 15:38

A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.

查看更多
浮光初槿花落
3楼-- · 2018-12-31 15:38

Dictionary class is not optimized for this case, but if you really wanted to do it (in C# 2.0), you can do:

public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)
{
   List<TKey> ks = new List<TKey>();
   foreach(TKey k in dict.Keys)
   {
      if (dict[k] == val) { ks.Add(k); }
   }
   return ks;
}

I prefer the LINQ solution for elegance, but this is the 2.0 way.

查看更多
登录 后发表回答