C#中的双向/双向字典? [英] Two-way / bidirectional Dictionary in C#?
本文介绍了C#中的双向/双向字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过以下方式在字典中存储单词:
I want to store words in a dictionary in following way:
我可以逐字获取字码:dict["SomeWord"]
-> 123
并逐字码:dict[123]代码> -> <代码>SomeWord"
I can get word code by word: dict["SomeWord"]
-> 123
and get word by word code: dict[123]
-> "SomeWord"
是真的吗?当然,一种方法是使用两个字典:Dictionary
和 Dictionary
但还有另一种方法吗?
Is it real? Of course one way to do it is two dictionaries: Dictionary<string,int>
and Dictionary<int,string>
but is there another way?
推荐答案
我快速编写了几个类,让您可以随心所欲.您可能需要使用更多功能对其进行扩展,但这是一个很好的起点.
I wrote a quick couple of classes that lets you do what you want. You'd probably need to extend it with more features, but it is a good starting point.
代码的使用如下:
var map = new Map<int, string>();
map.Add(42, "Hello");
Console.WriteLine(map.Forward[42]);
// Outputs "Hello"
Console.WriteLine(map.Reverse["Hello"]);
//Outputs 42
定义如下:
public class Map<T1, T2>
{
private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();
public Map()
{
this.Forward = new Indexer<T1, T2>(_forward);
this.Reverse = new Indexer<T2, T1>(_reverse);
}
public class Indexer<T3, T4>
{
private Dictionary<T3, T4> _dictionary;
public Indexer(Dictionary<T3, T4> dictionary)
{
_dictionary = dictionary;
}
public T4 this[T3 index]
{
get { return _dictionary[index]; }
set { _dictionary[index] = value; }
}
}
public void Add(T1 t1, T2 t2)
{
_forward.Add(t1, t2);
_reverse.Add(t2, t1);
}
public Indexer<T1, T2> Forward { get; private set; }
public Indexer<T2, T1> Reverse { get; private set; }
}
这篇关于C#中的双向/双向字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文