使用SelectListitem无法获得不同的值 [英] Cannot get distinct values using a SelectListitem
本文介绍了使用SelectListitem无法获得不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为下拉列表获取不同的值,但是当使用以下语法时,它将带回所有行.
I'm trying to get distinct values for a dropdownlist, but when using the following syntax, it brings me back all the rows.
有人可以告诉我如何使用正确的语法获取不同的值集吗?
Can someone please inform me how to get a distinct value set with the correct syntax?
IEnumerable<SelectListItem> ldidList = _db.TrafficHits.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
}).Distinct();
推荐答案
当前代码的问题是Distinct
将对SelectListItem
使用默认比较器.您将需要提供一个自定义比较器,如下所示:-
The problem with your current code is that Distinct
will use the default comparer for SelectListItem
. You will need to provide a custom comparer like this:-
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
然后您可以像这样使用它:-
Then you can use it like this:-
IEnumerable<SelectListItem> ldidList = _db.TrafficHits.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
}).Distinct(new SelectListItemComparer());
这篇关于使用SelectListitem无法获得不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文