First of all, we should come to terms: what are duplicates of
KeyValuePair<byte[], string>
instances. Assuming that KeyValuePair<byte[], string>
instances x
and y
are duplicate if and only if both Key
s and Value
s are equal, i.e.
x.Key.SequenceEquals(y.Key) && x.Value == y.Value
we can implement a required comparer:
public sealed class MyEquComparer : IEqualityComparer<KeyValuePair<byte[], string>> {
public bool Equals(KeyValuePair<byte[], string> x, KeyValuePair<byte[], string> y) =>
Enumerable.SequenceEqual(x.Key, y.Key) && string.Equals(x.Value, y.Value);
public int GetHashCode([DisallowNull] KeyValuePair<byte[], string> obj) =>
obj.Key == null ? 0 : obj.Key.Length;
}
And then using the comparer get rid of duplicates:
private static List<KeyValuePair<byte[], string>> list =
new List<KeyValuePair<byte[], string>>();
private static HashSet<KeyValuePair<byte[], string>> unique = new
HashSet<KeyValuePair<byte[], string>>(new MyEquComparer());
public static void AddTest(byte[] myarray, string test)
{
// only if we're adding a unique item, we put it into the list
if (unique.Add(test))
list.Add(new KeyValuePair<byte[], string>(myarray, test));
}