I have a IEnumerable
of objects that have redefined GetHashCode
method. I assumed that if I add those objects to HashSet<T>
, it would hold only the unique objects. But it doesn't:
var set = new HashSet<SomeObject>();
Count = 0
set.Add(first);
true
set.Add(second);
true
set.Count
2
first.GetHashCode()
-927637658
second.GetHashCode()
-927637658
So how could I reduce my IEnumerable
structure of objects to those that are unique based on their GetHashCode()
value.
Although I don't know if this helps in any way:
public class SomeObject
{
...
public string GetAggregateKey()
{
var json = ToJson();
json.Property("id").Remove();
return json.ToString(); // without the `id`, the json string of two separate objects with same content could be the same
}
override public int GetHashCode()
{
// two equal strings have same hash code
return GetAggregateKey().GetHashCode();
}
...
}