独特的在LINQ不工作 [英] distinct not working in linq

查看:57
本文介绍了独特的在LINQ不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想为以下查询获取不同的EmployeeId.我使用了Distinct,但无法正常使用

Hi
i want to get the distinct EmployeeId for the following query. I used Distinct but its not working

var emp= (from dr in dt.AsEnumerable() orderby dr["EmployeeID"] descending
         select new Employee(){
EmployeeId = int.Parse(dr"EmployeeID"].ToString()),     
EmployeeName = dr["EmployeeName"].ToString(),
EmployeeDesignation = dr["EmployeeDesignation"].ToString()
         }).Distinct();

推荐答案

因为添加了".而且仍然无法正常工作,我想您的课程无法实现IEquatable.
这意味着Distinct将使用默认的比较器,对于一个类,该比较器是引用比较.由于您的所有实例都是new实例,因此它们都将通过引用比较而失败,因为引用不相同.

您需要实现IEquatable< Employee>.并提供Equals方法(猜测是比较EmployeeID值)和GetHashCode方法,或为Distinct调用提供自定义比较器:
Since you have added the "." and it''s still not working, I am guessing that your class does not implement IEquatable.
What that means is that Distinct will use the default comparer, which for a class is a Reference comparison. Since all your instances are new instances, they will all fail a reference comparison, because the references are not the same.

You need to either implement IEquatable<Employee> and provide the Equals method (at a guess comparing EmployeeID values) and the GetHashCode method, or provide a custom comparer to the Distinct call: http://msdn.microsoft.com/en-us/library/bb338049.aspx[^] describes it and provides an example.


您需要在单词前加上.''.'' 不同":
You need a ''.'' before the word "Distinct":
var emp= (from dr in dt.AsEnumerable() orderby dr["EmployeeID"] descending
         select new Employee(){
EmployeeId = int.Parse(dr"EmployeeID"].ToString()),
EmployeeName = dr["EmployeeName"].ToString(),
EmployeeDesignation = dr["EmployeeDesignation"].ToString()
         })Distinct();

成为:

var emp= (from dr in dt.AsEnumerable() orderby dr["EmployeeID"] descending
         select new Employee(){
EmployeeId = int.Parse(dr"EmployeeID"].ToString()),
EmployeeName = dr["EmployeeName"].ToString(),
EmployeeDesignation = dr["EmployeeDesignation"].ToString()
         }).Distinct();


为什么会起作用.

Why it will work.

var emp= (from dr in dt.AsEnumerable() orderby dr["EmployeeID"] descending
         select new Employee(){
EmployeeId = int.Parse(dr"EmployeeID"].ToString()),     
EmployeeName = dr["EmployeeName"].ToString(),
EmployeeDesignation = dr["EmployeeDesignation"].ToString()
         }).Distinct();


这篇关于独特的在LINQ不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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