且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用SelectListitem无法获得不同的值

更新时间:2023-11-07 11:58:40

当前代码的问题是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());