How to get a TValue dictionary from TKey in C #?

I declared the obj dictionary.

Dictionary<string, string> aDict = new Dictionary<string, string>(); 
        aDict .Add("IP", "Host"); 

As I remember,

An expression aDict[IP]can return a value (Host).

Now if I go in the opposite direction.

How to get a key to the cost? aDict[Host]?

Is the dictionary a one-way street in C # but only works from Key to Value? thank.

+3
source share
4 answers

Dictionaries do not work like them. How do you decide the following:

key = "1", value = "x",
key = "2", value = "x"

You can do it:

var keys = dict.Where(kvp => kvp.Value == someValue).Select(kvp => kvp.Key);
foreach(var key in keys) {
    Console.WriteLine(key);
}

, . , :

class TwoWayDictionary<TLeft, TRight> {
    IDictionary<TLeft, TRight> leftToRight = new Dictionary<TLeft, TRight>();
    IDictionary<TRight, TLeft> rightToLeft = new Dictionary<TRight, TLeft>();

    public void Add(TLeft left, TRight right) {
        if (leftToRight.ContainsKey(left)) {
            throw new InvalidOperationException("key left is duplicate");
        }
        if (rightToLeft.ContainsKey(right)) {
            throw new InvalidOperationException("key right is duplicate");
        }
        leftToRight.Add(left, right);
        rightToLeft.Add(right, left);
    }

    public bool TryGetRightByLeft(TLeft left, out TRight right) {
        return leftToRight.TryGetValue(left, out right);
    }

    public bool TryGetLeftByRight(out TLeft left, TRight right) {
        return rightToLeft.TryGetValue(right, out left);
    }
}

, , .

:

TwoWayDictionary<string, string> dict = new TwoWayDictionary<string, string>();
dict.Add("127.0.0.1", "localhost");

string host;
dict.TryGetRightByLeft("127.0.0.1", out host);
// host is "localhost"

string ip;
dict.TryGetLeftByRight("localhost", out ip);
// ip is "127.0.0.1"
+19

- . - , "", . , .

+3

. , , :

 foreach(string s in Dict.Keys)
 {
   if(Dict[s] == TheValue)
       ;//we found it!
 }
+1

, - . , "", .

However, you can iterate over the dictionary, noting which keys correspond to the required value:

foreach (var entry in dict)
{
  if (entry.Value == desiredValue)
    found.Add(entry.Key);
}

Obviously, this is inefficient for large dictionaries.

+1
source

Source: https://habr.com/ru/post/1727443/


All Articles