从3个整数值创建字典键

时间:2016-10-20 13:36:52

标签: c# performance dictionary unique-key

我有一个有3个整数值的对象,3个整数总是唯一的。我想快速找到成千上万的具体对象。

我的想法是将3个整数组合成一个字符串,这样1,2533和9将成为一个唯一的字符串:1-2533-9。但这是最有效的方式吗?数字不能大于2 ^ 16,所以我也可以使用位移并创建一个long,这比我想的更快。还有其他选择吗?我该怎么办?

我想要实现的主要目标是即使使用数千个对象的集合也能快速找到对象。

1 个答案:

答案 0 :(得分:0)

public class SomeClass
{
    private readonly IDictionary<CompositeIntegralTriplet, object> _dictionary = new Dictionary<CompositeIntegralTriplet, object>();
}

public sealed class CompositeIntegralTriplet : IEquatable<CompositeIntegralTriplet>
{
    public CompositeIntegralTriplet(int first, int second, int third)
    {
        First = first;
        Second = second;
        Third = third;
    }

    public int First { get; }
    public int Second { get; }
    public int Third { get; }

    public override bool Equals(object other)
    {
        var otherAsTriplet = other as CompositeIntegralTriplet;
        return Equals(otherAsTriplet);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = First;
            hashCode = (hashCode*397) ^ Second;
            hashCode = (hashCode*397) ^ Third;
            return hashCode;
        }
    }

    public bool Equals(CompositeIntegralTriplet other) => other != null && First == other.First && Second == other.Second && Third == other.Third;
}