LINQ - Distinct is ignored?

感情迁移 提交于 2020-01-15 04:35:07

问题


So I have a problem with my LINQ code, where I have to select a Distinct data set, I implement the following IEqualityComparer:

public class ProjectRoleComparer : IEqualityComparer<ProjectUserRoleMap>
{
    public bool Equals(ProjectUserRoleMap x, ProjectUserRoleMap y)
    {
        return x.RoleID.Equals(y.RoleID);
    }
    public int GetHashCode(ProjectUserRoleMap obj)
    {
        return obj.GetHashCode();
    }
}

In this context, I wish to retrieve a bunch of ProjectUserRoleMap objects related to a given Project, identified by it's ID, I only want one ProjectUserRoleMap per unique RoleID, but my strict instruction to perform a distinct select on the RoleID is ignored. I am totally clueless as to why this is the case, and do not understand LINQ enough to think of a workaround. Here is the calling code:

ProjectRoleComparer prCom = new ProjectRoleComparer();

IEnumerable<ProjectUserRoleMap> roleList = ProjectData.AllProjectUserRoleMap.Where(x => x.ProjectID == id).Distinct(prCom);

This code gives me 6 entries, when the number of entries I know I want is just 4. Am I doing something wrong with my usage of LINQ?

For reference, the ProjectUserRoleMap object has a RoleID, (int)


回答1:


Your implementation of GetHashCode is wrong. Return obj.RoleID.GetHashCode();

Background:
Code that consumes an IEqualityComparer<T> usually first compares the hash codes of two objects. Only if those hash codes are the same Equals is called.
It is implemented like this, because two unequal objects can have the same hash key, but two equal objects never can have different hash keys - if GetHashCode() is implemented correctly.
This knowledge is used to improve the efficiency and performance of the comparison as implementations of GetHashCode are supposed to be fast, cheap operations.




回答2:


Try:

public int GetHashCode(ProjectUserRoleMap obj)
{
    return obj.RoleID.GetHashCode();
}


来源:https://stackoverflow.com/questions/16147886/linq-distinct-is-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!