Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

Try:

public int GetHashCode(ProjectUserRoleMap obj)
{
    return obj.RoleID.GetHashCode();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top