【问题标题】:How to combine 2 ints to make a unique dictionary key如何组合 2 个整数来制作唯一的字典键
【发布时间】:2015-02-20 00:09:02
【问题描述】:

我正在尝试从 2 个整数中创建一个字典键,我正在考虑将它们组合如下 2 和 3 ---> 23 21 和 34 ---> 2134 等等等等

如何实现这一点,如果这是一种不好的方法,那还有什么更好的方法?

提前致谢

【问题讨论】:

  • 使用此方案您将遇到的第一个问题是例如 (2,134) 与 (21,34) 与 (213,4) 之间的冲突。
  • 啊,我真的没有考虑过。谢谢
  • 创建一个具有两个 int 作为属性的类,并将其作为您的键。
  • 您可以将键数据类型更改为字符串吗?...然后将它们与分隔符组合:21,34
  • 感谢大家的建议。这是针对流体模拟的,因此需要性能影响最小的选项。有谁知道建议的方法中哪个更快?

标签: c# dictionary key


【解决方案1】:

以下结构组合了两个整数并覆盖相等成员以使其可用作字典中的键。这个解决方案比我之前使用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 次写入或读取大约需要 250 毫秒。

【讨论】:

  • 非常感谢。这很棒。只有一个问题。那么我将如何从密钥中获取 x 和 y?
  • 我添加了一些吸气剂。查看修改后的答案。
【解决方案2】:

如果您知道 int 数的最大值,比如 256,那么您可以这样做

firstInt * 256 + secondInt

以上将为您提供具有 int 性能优势的唯一编号。

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

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 2018-10-03
    • 2015-01-11
    • 2011-05-14
    • 1970-01-01
    • 2020-05-30
    • 2021-01-21
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多