如何组合2个整数来制作一个独特的字典键

时间:2014-12-21 20:22:59

标签: c# dictionary key

我正在尝试从2个整数创建字典密钥,我想将它们组合如下 2和3 ---> 23 21和34 ---> 2134 等等

如何实现这一点,如果这是一个糟糕的方法,那会更好一点?

提前致谢

2 个答案:

答案 0 :(得分:2)

以下结构组合了两个整数并覆盖了相等成员,使其可用作字典中的键。此解决方案比使用Tuple<T1,T2>的先前提案更快,并且比使用long更不容易出错。

public struct IntKey
{
    private readonly int first;
    private readonly int second;

    public int First { get { return first; } }
    public int Second { get { return second; } }

    public IntKey(int first, int second)
    {
        this.first = first;
        this.second = second;
    }

    public bool Equals(IntKey other)
    {
        return this.first == other.first && this.second == other.second;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        return obj is IntKey && Equals((IntKey) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (this.first*397) ^ this.second;
        }
    }
}

[TestClass]
public class DictionaryTests
{
    [TestMethod]
    public void Test()
    {
        var dictionary = new Dictionary<IntKey, string>();

        for (int j = 0; j < 3; j++)
        {
            dictionary.Clear();
            var watch = Stopwatch.StartNew();

            for (int i = 0; i < 1000000; i++)
            {
                dictionary.Add(new IntKey(i, i), "asdf");
            }

            Console.WriteLine(watch.ElapsedMilliseconds);
            watch.Restart();

            for (int i = 0; i < 1000000; i++)
            {
                var value = dictionary[new IntKey(i, i)];
            }

            Console.WriteLine(watch.ElapsedMilliseconds);
        }
    }
}

试试吧。在我的Azure VM上,1,000,000次写入或读取大约需要250ms。

答案 1 :(得分:0)

如果你知道你的int数的最大值,比如说256就可以了

firstInt * 256 + secondInt

以上将给出具有int性能优势的唯一编号。

只需反转计算即可取回两个数字