Not-hash-based set collection for storing unique objects with custom equality comparer - C# -
i'm trying store (name: string, value: long) pair in set.
public class namevaluepair { public string name; public long value; } public namevaluepaircomparer comparer = new namevaluepaircomparer(); public hashset<namevaluepair> namevalueset = new hashset<namevaluepair>(comparer);
two pairs equal if either have equal name or equal value - implemented in namevaluepaircomparer overriding equals method equalitycomparer:
public class namevaluepaircomparer : equalitycomparer<namevaluepair> { public override bool equals(namevaluepair x, namevaluepair y) { return (x.value == y.value) || (x.name == y.name); }
the problem is: gethashcode(namevaluepair obj) should return same value 2 objects equals return true, given namevaluepair, gethashcode() should return either value.gethashcode() or name.gethashcode(), have know field in both pairs equal:
public override int gethashcode(namevaluepair obj) { /* ??? */ /* // using unknown reference x if (obj.value == x.value) return obj.value.gethashcode(); else if (obj.name == x.name) return obj.name.gethashcode(); else return base.gethashcode(obj); */ } }
but can't know this, , means can't use hashset store these pairs nor equalitycomparer.
q: there not-hash-based implementation of set in c# (.net 3.5) ?
q: better approach storing unique namevaluepairs custom equality comparer ?
two pairs equal if either have equal name or equal value
you fundamentally can't implement iequalitycomparer<t>
correctly these criteria. documentation of equals
:
the equals method reflexive, symmetric, , transitive. is, returns true if used compare object itself; true 2 objects x , y if true y , x; , true 2 objects x , z if true x , y , true y , z.
now consider pairs:
x = { "a", 10 }, y = { "a", 20 }, z = { "b", 20 }
you're saying x
, y
must equal have same name, , y
, z
must equal have same value. means (by transitivity) x
, z
should equal.
as can't implement iequalitycomparer<t>
correctly, shouldn't expect relies on correctness work.
i suspect you'll find if @ requirements in more detail, either call 2 collections (one name, 1 value) or don't make sense in light of transitivity.
for example, imagine had set characteristics you've suggested, , add 3 elements above. if add them in order { x, y, z } you'd end single entry. if add them in order { z, x, y } you'd end two. how useful kind of set?
Comments
Post a Comment