2014-12-21 44 views
0

我想从2个整数字典键,我想要结合它们如下 2和3 ---> 23 21和34 --- > 2134 etc等如何结合2个整数来创建一个唯一的字典键

如何实现这一目标,如果这是一个不好的方法,那会更好吗?

在此先感谢

+0

你会用这个方案遇到的第一个问题是,例如之间的碰撞,(2134)和(21,34)和(213,4)。 –

+0

啊,我其实没有考虑这个。谢谢 – KMoore

+0

做一个有两个整数作为属性的类,并且创建你的密钥。 – dbugger

回答

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虚拟机上,1,000,000次写入或读取需要大约250ms。

+0

非常感谢。这很棒。只有一个问题。那么我将如何从密钥中获得x和y? – KMoore

+0

我添加了一些getters。查看修改后的答案 – Frank

0

如果你知道你的INT数的最大值,比如256,那么你可以做

firstInt * 256 + secondInt

上述会给你的INT的性能优势唯一编号。

只需反向计算拿回两个数字

相关问题