LINQ - 分明被忽略? [英] LINQ - Distinct is ignored?

查看:270
本文介绍了LINQ - 分明被忽略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个问题,我的LINQ code,在那里我必须选择一个不同的数据集,我实现以下的IEqualityComparer

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();
    }
}

在这种情况下,我想找回一堆 ProjectUserRoleMap 对象涉及到一个给定的项目,确定了它的ID,我只想要一个 ProjectUserRoleMap 每个唯一 RoleID ,但我的严格指令来执行不同的选择上的 RoleID 被忽略。我完全无能,为什么是这样的情况下,不明白LINQ意犹未尽地想起一种解决方法。这里是调用code:

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);

这code给我6项,当我的项的数目知道我要的只是4 难道我做错了什么我使​​用LINQ的?

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?

有关参考, ProjectUserRoleMap 对象有一个RoleID,(INT)

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

推荐答案

您实施 GetHash code 是错误的。返回 obj.RoleID.GetHash code();

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

背景:
code,消耗了的IEqualityComparer&LT; T&GT; 一般先比较两个对象的散列codeS。只有当这些散列codeS是相同的等于被调用。
它是这样实现的,因为两个不等的对象可以具有的一样的哈希键,而是两个的等于的对象永远不能拥有的不同的的哈希键 - 如果 GetHash code()正确实现
。 这方面的知识是用来改善所述比较为 GetHash code 的实施方案的效率和性能应该是快速,廉价的操作。

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.

这篇关于LINQ - 分明被忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆