Created
February 17, 2019 08:52
-
-
Save mjs3339/76b530586154f63b799bb4aa060a5179 to your computer and use it in GitHub Desktop.
C# Generic IEqualityComparer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Serializable] | |
private class ArrayComparer<T> : IEqualityComparer<T> | |
{ | |
private static Type _type; | |
private static int _size; | |
public bool Equals(T x, T y) | |
{ | |
if(x == null || y == null) | |
return false; | |
if(_type == null) | |
_type = x.GetType(); | |
return _type.IsArray ? Converters.GetBytesObject(x, _type).Compare(Converters.GetBytesObject(y, _type)) : x.Equals(y); | |
} | |
public int GetHashCode(T item) | |
{ | |
if(_type == null) | |
{ | |
_type = item.GetType(); | |
_size = Converters.GetBytesObject(item, _type).Length; | |
} | |
return _type.IsArray ? Converters.GetBytesObject(item, _type).Aggregate(397, (current, b) => (current ^ b.GetHashCode()) * 31) ^ _size : (397 ^ item.GetHashCode()) * 31; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment