2014-12-21 43 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的性能優勢唯一編號。

只需反向計算拿回兩個數字

相關問題