如何在 C# 中从 TKey 获取字典 TValue?

发布于 2024-08-16 22:04:46 字数 351 浏览 6 评论 0原文

我声明了字典 obj。

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

我记得,

aDict[IP] 的表达式可以返回值(Host)。

现在如果我朝相反的方向走。

如何从Value中获取Key? aDict[主机]

Dictionary 是 C# 中的一条单向街道,仅从 Key 到 Value 运行吗?谢谢。

I declared the dictionary obj.

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

As I remembered,

The expression of aDict[IP] can return the value (Host).

Now if I go in the opposite direction.

How to get the Key from Value ? aDict[Host] ?

Does the Dictionary is a one-way street in C#, only running from Key to Value ? thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

念三年u 2024-08-23 22:04:46

字典不是这样工作的,也不是有意这样工作的。您将如何解决以下问题:

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

您可以这样做:

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"

Dictionaries do not work like this, nor are they intended to. How would you resolve the following:

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

You could do this:

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

But if you really need to go back and forth between keys and values you should consider encapsulating the problem into a two-way map. Here's a very simple implementation of this that you can tailor to your needs:

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);
    }
}

Note that this assumes that no key is ever duplicated.

Now you can say:

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"
背叛残局 2024-08-23 22:04:46

字典是一种单向查找。如果需要,您仍然可以循环遍历字典中的所有条目来查找值“Host”。如果您预计会经常这样做,您可能只想使用两个字典并使它们保持同步。

Dictionary is a one way lookup. You can still loop over all entries in the Dictionary looking for the value "Host" if you need to. If you anticipate doing that a lot you might just want to use two dictionaries to and keep them both in sync.

故事↓在人 2024-08-23 22:04:46

是的,字典基本上是一条单行道。例如,许多键可能具有值“Host”,因此没有简单的反向查找。

但是,您可以迭代字典,注意哪些键映射到所需的值:

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

显然,这对于大型字典来说效率不高。

Yes, the dictionary is basically a one way street. For example, it would be possible for many keys to have the value "Host", so there's no simple reverse lookup.

However, you can iterate over the dictionary noting which keys map to the desired value:

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

Obviously this is not efficient for large dictionaries though.

锦欢 2024-08-23 22:04:46

这是一条单向街道。值不应该是唯一的,因此您不能按值查找键,除非枚举整个字典:

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

It is a one way street. Values are not supposed to be unique, so you cannot look up a key by value, except by enumerating the whole dictionary:

 foreach(string s in Dict.Keys)
 {
   if(Dict[s] == TheValue)
       ;//we found it!
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文