包含两个项目并且可以相互返回的数据结构列表

时间:2016-01-02 19:46:28

标签: c# list

我有一个printf("Bytes received %d\n",bytesReceived);,其中dictionary为关键字,int为值。

我可以通过string获取string。我想要的是一个数据结构,它使我能够通过赋予int来获得int

所以我希望它能同时发挥作用。我该怎么用?

哦,我知道每个int和每个字符串都是唯一的。

3 个答案:

答案 0 :(得分:2)

如果值是唯一的,则您不需要其他数据结构:

var dict = new Dictionary<int, string> { { 1, "a" }, { 2, "b" }, { 3, "c" } };
Console.WriteLine(dict[1]); // a

var res = dict.Keys.FirstOrDefault(k => dict[k] == "a");
Console.WriteLine(res); // 1

答案 1 :(得分:1)

构建一个内部使用两个词典的自定义数据类型,一个Dictionary<int, string>和一个Dictionary<string, int>

class TwoWayDictionary<T1, T2>
{
    IDictionary<T1, T2> dic1 = new Dictionary<T1, T2>();
    IDictionary<T2, T1> dic2 = new Dictionary<T2, T1>();

    public T2 this[T1 key]
    {
        get
        {
            return dic1[key];
        }
        set
        {
            dic1[key] = value;
            dic2[value] = key;
        }
    }

    public T1 this[T2 key]
    {
        get
        {
            return dic2[key];
        }
        set
        {
            dic2[key] = value;
            dic1[value] = key;
        }
    }

    public void Remove(T1 key)
    {
        var value = dic1[key];
        dic1.Remove(key);
        dic2.Remove(value);
    }

    public void Remove(T2 key)
    {
        var value = dic2[key];
        dic2.Remove(key);
        dic1.Remove(value);
    }

    public void Add(T1 key, T2 value)
    {
        dic1.Add(key, value);
        dic2.Add(value, key);
    }
}

答案 2 :(得分:0)

我做到了这一点并且有效:

public class customDict<TValue> : Dictionary<int, TValue> where TValue : class
{
    public int this[TValue index]
    {
        get
        {
            var retVal = this.Where(e => e.key == index);
            if (retVal.Count() == 1)
            {
                return retVal.First().Value;
            }else
            {
                return default(TValue);
            }
        }
    }
}

我在这段代码中使用了它

var x = new customDict<string>();
x.Add(0, "Bubba");
var alwaysWorked= x[0];
var nowWorks= x["Bubba"];

重新阅读后编辑...