[英]Not getting Distinct Items when using Linq to List?
Here is how I am attempting to get a distinct List of items... 这是我试图获得一个独特的项目列表...
var queryResults = PatientList.Distinct();
PatientList = queryResults.ToList<SelectListItem>();
For some reason, I am not getting a distinct list here. 出于某种原因,我在这里没有得到明确的清单。
Use 采用
var queryResults = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault())
PatientList = queryResults.ToList<SelectListItem>();
You can always try 你可以随时试试
PatientList = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).ToList<SelectListItem>();
It will give you the distinct results based off whatever you group by 它将根据您分组的任何内容为您提供截然不同的结果
Check out http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx 查看http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
Also another question for reference: Returning a Distinct IQueryable with LINQ? 还有一个问题需要参考: 用LINQ返回一个独特的IQueryable?
Not sure what kind of items your PatientList contains, but I guess you have to implement IEquatable on your custom object. 不确定您的PatientList包含哪些项目,但我猜您必须在自定义对象上实现IEquatable。
This have been aswered before here: Distinct not working with LINQ to Objects 这之前已经解决了:明确不使用LINQ to Objects
Your SelectListItem
class needs to override Equals
and GetHashCode
(and optionally implement IEquatable<SelectListItem>
). 您的
SelectListItem
类需要重写Equals
和GetHashCode
(并且可选地实现IEquatable<SelectListItem>
)。 Otherwise, different instances with the same values will be considered different. 否则,具有相同值的不同实例将被视为不同。
Another option is to implement a IEqualityComparer<SelectListItem>
and pass it as the second parameter to Distinct
. 另一种选择是实现
IEqualityComparer<SelectListItem>
并将其作为第二个参数传递给Distinct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.