Can't get individual values ββusing SelectListitem
I'm trying to get different values ββfor a dropdown, but when using the following syntax, it returns me all the rows.
Can someone please tell me how to get a great value with the correct syntax?
IEnumerable<SelectListItem> ldidList = _db.TrafficHits.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.ldid
}).Distinct();
source to share
The problem with your current code is what the Distinct
default mapper will use for SelectListItem
. You will need to provide a custom matcher, for example:
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());
source to share
I'm pretty sure it SelectListItem
doesn't have equal values ββ(i.e. does not override Equals
). Each of them will be equal to a reference, so none of your elements will be equal, even if they have the same value.
Assuming your hits are unique Id
, try:
var items = _db.TrafficHits
.GroupBy(h => h.Id)
.Select(g => new SelectListItem
{
Value = g.Key.ToString(),
Text = g.First().ldid
});
source to share