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();

      

+3


source to share


3 answers


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());

      

+5


source


You can use a group, then you select the first item for each 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
                                         });

      

+2


source


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
    });

      

+1


source







All Articles