Wednesday 20 September 2017

Cannot get distinct values using a SelectListitem

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

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive