Hi all i’cant figure out why its not working need some help. I have a list with links and some data i want to distinct list by link host here the code
public class DataContainerEqualityComparer : IEqualityComparer<DataContainer>
{
public bool Equals(DataContainer x, DataContainer y)
{
return x.Url.Host == y.Url.Host;
}
public int GetHashCode(DataContainer obj)
{
return obj.Url.GetHashCode();
}
}
List<DataContainer> items = new List<DataContainer>();
var item = new DataContainer("http://google.com/123");
items.Add(item);
item = new DataContainer("http://google.com/1234");
items.Add(item);
item = new DataContainer("http://google.com/12345");
items.Add(item);
item = new DataContainer("http://google.com/123456");
items.Add(item);
item = new DataContainer("http://google.com/1234567");
items.Add(item);
items = items.Distinct(new DataContainerEqualityComparer()).ToList();
after this nothing happens. Thx in advance.
The problem with your implementation of
DataContainerEqualityCompareris that you are returning the hash code of the Url and not that of the Host.Change it to this and it should work as expected:
When checking two objects for equality the following happens:
First,
GetHashCodeis called on both objects. If the hash code is different, the objects are considered not equal andEqualsis never called.Equalsis only called whenGetHashCodereturned the same value for both objects.