Get Dictionary key by using the dictionary value

前端 未结 5 1288
盖世英雄少女心
盖世英雄少女心 2020-12-28 14:40

How to get the dictionary key by using the dictionary value?

when getting the value using the key its like this:

Dictionary dic =          


        
5条回答
  •  -上瘾入骨i
    2020-12-28 15:23

    easy way for get one key:

        public static TKey GetKey(Dictionary dictionary, TValue Value)
        {
            List KeyList = new List(dictionary.Keys);
            foreach (TKey key in KeyList)
                if (dictionary[key].Equals(Value))
                    return key;
            throw new KeyNotFoundException();
        }
    

    and for multiples keys:

        public static TKey[] GetKeys(Dictionary dictionary, TValue Value)
        {
            List KeyList = new List(dictionary.Keys);
            List FoundKeys = new List();
            foreach (TKey key in KeyList)
                if (dictionary[key].Equals(Value))
                    FoundKeys.Add(key);
            if (FoundKeys.Count > 0)
                return FoundKeys.ToArray();
            throw new KeyNotFoundException();
        }
    

提交回复
热议问题