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 DataContainerEqualityComparer
is 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:
public int GetHashCode(DataContainer obj)
{
return obj.Url.Host.GetHashCode();
}
When checking two objects for equality the following happens:
First, GetHashCode
is called on both objects. If the hash code is different, the objects are considered not equal and Equals
is never called .
Equals
is only called when GetHashCode
returned the same value for both objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.