c# - 元组(或数组)作为 C# 中的字典键

标签 c# dictionary hashtable tuples

我正在尝试用 C# 制作字典查找表。我需要将 3 元组值解析为一个字符串。我尝试使用数组作为键,但这没有用,我不知道还能做什么。在这一点上,我正在考虑制作一个字典的字典,但看起来可能不是很漂亮,尽管这是我在 javascript 中的做法。

最佳答案

如果您使用的是 .NET 4.0,请使用元组:

lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();

如果没有,您可以定义一个 Tuple 并将其用作键。元组需要覆盖 GetHashCodeEqualsIEquatable:

struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
{
    readonly T first;
    readonly U second;
    readonly W third;

    public Tuple(T first, U second, W third)
    {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T First { get { return first; } }
    public U Second { get { return second; } }
    public W Third { get { return third; } }

    public override int GetHashCode()
    {
        return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        return Equals((Tuple<T, U, W>)obj);
    }

    public bool Equals(Tuple<T, U, W> other)
    {
        return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
    }
}

关于c# - 元组(或数组)作为 C# 中的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/955982/

相关文章:

c# - 将对象转换为 IEnumerable

c# - 在 C# 中处理非常大的整数

c# - 命名空间在 C# 中是必不可少的吗?

c# - 添加到字典中的值

python - 将三级定界的字符串解析成字典

c++ - boost 函数映射到字符串

c - size_t 预处理器值的大小

c# - 具有采用不同泛型类的方法的泛型类

delphi - 指向泛型类型的指针

c - 使用哈希表获取节点