简体   繁体   English

如何在c#中使用字典两种方式

[英]how to use dictionary two way in c#

public static Dictionary<int, string> dic = new Dictionary<int, string>() { 
            {1,"anystring1"},
            {2,"anystring2"}};

I need to use this 我需要用这个

string str= dic[1]; // it is possible

int a=dic["anystring1"]; // My dream is it

使用另一个Dictionary<>并以键/值的相反顺序使用它。

I'm a bit late on this one, but LINQ is your friend here: 我在这一点上有点晚了,但LINQ是你的朋友:

MyDict.FirstOrDefault(pair => pair.Value == "the value you want").Key;

Allows you to do what you want. 让你做你想做的。

I wish this was in the System library, but it's pretty easy to roll your own. 我希望这是在系统库中,但是很容易推出自己的库。

Below, I'll provide the skeleton of writing such a class, whose usage looks like: 下面,我将提供编写这样一个类的框架,其用法如下:

var twoWayDict = new TwoWayDict<string, int>();

twoWayDict["zero"] = 0;
// twoWayDict["zero"] == 0
// twoWayDict.Reverse[0] == "zero"

twoWayDict.Reverse[1] = "one";
// twoWayDict["one"] == 1
// twoWayDict.Reverse[1] == "one"

Keep in mind, one gotcha for a two way dictionary is that you should expect all input to be tightly coupled. 请记住,双向字典的一个问题是,您应该期望所有输入都紧密耦合。 In other words, if you re-use a key OR a value, you will erase the data previous linked with either: 换句话说,如果您重新使用一个键或一个值,您将删除之前链接的数据:

twoWayDict["zero"] = 0;

// Then later...
twoWayDict.Reverse[0] = "ZERO";
// Now twoWayDict["ZERO"] == 0

// Later still...
// Exception: Key not found! "zero" was dropped when you re-used value 0
Console.WriteLine(twoWayDict["zero"]); 

Finally, here's some sample code. 最后,这里有一些示例代码。 It's minimal - it should act as a foundation for anyone who wants to flesh out their own version. 这是最小的 - 它应该成为任何想要充实自己版本的人的基础。 Note that I implement a wrapper class so I can provide a "Reverse" property without directly exposing the internal dictionary. 请注意,我实现了一个包装类,因此我可以提供“反向”属性而不直接公开内部字典。

// Generics note: K indicates "key" type and V indicates "value" type
using System.Collections.Generic;

namespace YourNamespaceHere.Collections
{
  public class TwoWayDict<K, V>
  {
    private Dictionary<K, V> _dictKV;
    private Dictionary<V, K> _dictVK;
    private ReverseDict _reverseDict;

    public TwoWayDict()
    {
      _dictKV = new Dictionary<K, V>();
      _dictVK = new Dictionary<V, K>();
      _reverseDict = new ReverseDict(this);
    }

    public ReverseDict Reverse
    {
      get { return _reverseDict; }
    }

    // TwoWayDict[key] -> value
    public V this[K key]
    {
      get { return _dictKV[key]; }
      set
      {
        // Remove any existing key/value pair
        Remove(key);

        _dictKV[key] = value;
        _dictVK[value] = key;
      }
    }

    public void Remove(K key)
    {
      if (_dictKV.ContainsKey(key))
      {
         _dictVK.Remove(_dictKV[key]);
         _dictKV.Remove(key);
      }
    }

    // Wrapper that allows TwoWayDict to expose a convenient
    // 'Reverse' property.
    public class ReverseDict
    {
      private TwoWayDict<K, V> _parent;
      public ReverseDict(TwoWayDict<K, V> parent)
      {
         _parent = parent;
      }

      public K this[V reverseKey]
      {
        get { return _parent._dictVK[reverseKey]; }
        set { _parent[value] = reverseKey; }
      }

      public void Remove(V value)
      {
        if (_parent._dictVK.ContainsKey(value))
        {
          _parent.Remove(_parent._dictVK[value]);
        }
      }
    }    
  }
}

That is not what a dictionary is meant to do. 这不是字典的意思。 Can you think of a definition and instantly find the matching word in your favorite dictionary in O(1) time? 你能想到一个定义,并在O(1)时间内在你最喜欢的词典中找到匹配的单词吗? If you want a class with that type of functionality (a bidirectional dictionary) you will have to build it yourself (or Google for one of many implementations on the Internet). 如果你想要一个具有这种功能的类(一个双向字典),你必须自己构建它(或者谷歌用于互联网上的许多实现之一)。

I actually use a class that combines an ArrayList with a Dictionary so that I can look up child nodes based on name or order added, and maintain the original order of the objects as they were added. 我实际上使用了一个将ArrayList和Dictionary组合在一起的类,这样我就可以根据添加的名称或顺序查找子节点,并在添加对象时保持原始顺序。

Objects are added to the ArrayList first, then the index of that object in the ArrayList is added to the dictionary using the desired key. 首先将对象添加到ArrayList,然后使用所需的键将ArrayList中该对象的索引添加到字典中。

This allows me to access either by key or position, in a very optimal way, while maintaining the order of the objects as they were added. 这允许我以非常优化的方式通过键或位置访问,同时在添加对象时保持对象的顺序。

Gotcha areas to watch for are adding another object using an existing key, which will orphan the original object and removing any element from the vector which will cause the indices in the Dictionary to become corrupted, pointing to the wrong values. 要注意的问题是使用现有密钥添加另一个对象,该密钥将孤立原始对象并从向量中删除任何元素,这将导致Dictionary中的索引损坏,指向错误的值。

Just thought I would share my two cents worth - hope it helps someone. 只是想我会分享我的两分钱 - 希望它能帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM