Use byte[] as key in dictionary

前端 未结 7 1618
南旧
南旧 2020-12-28 12:11

I need to use a byte[] as a key in a Dictionary. Since byte[] doesn\'t override the default GetHashCode method, two sepa

7条回答
  •  感动是毒
    2020-12-28 12:49

    By default byte[] will be compared by reference which is not what you want in this case. What you need to do is specify a custom IEqualityComparer and do the comparison you want.

    For example

    public class ByteArrayComparer : IEqualityComparer {
      public bool Equals(byte[] left, byte[] right) {
        if ( left == null || right == null ) {
          return left == right;
        }
        return left.SequenceEqual(right);
      }
      public int GetHashCode(byte[] key) {
        if (key == null)
          throw new ArgumentNullException("key");
        return key.Sum(b => b);
      }
    }
    

    Then you can do

    var dict = new Dictionary(new ByteArrayComparer());
    

    Solution for 2.0

    public class ByteArrayComparer : IEqualityComparer {
      public bool Equals(byte[] left, byte[] right) {
        if ( left == null || right == null ) {
          return left == right;
        }
        if ( left.Length != right.Length ) {
          return false;
        }
        for ( int i= 0; i < left.Length; i++) {
          if ( left[i] != right[i] ) {
            return false;
          }
        }
        return true;
      }
      public int GetHashCode(byte[] key) {
        if (key == null)
          throw new ArgumentNullException("key");
        int sum = 0;
        foreach ( byte cur in key ) {
          sum += cur;
        }
        return sum;
      }
    }
    

提交回复
热议问题