Cannot get distinct values using a 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());
You can use the group by, then you select the first element per group :
IEnumerable<SelectListItem> ldidList = _db.TrafficHits
.GroupBy(t => t.Id)
.Select(g => g.First())
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
});