2

Ok, aside from the silly title. I have a query pulling back distinct values but it is including the departmentID column instead of the departmentName column as distinct. Which makes me sometimes causes duplicates.

ViewBag.DepartmentList = docs.Select(m => new SelectListItem
            {
                Value = SqlFunctions.StringConvert((double)m.departmentID).Trim(),
                Text = m.departmentName
            })
            .Distinct(); //  Fill the viewbag with a unique list of 'Department's from the table.

Here is what the docs has inside it:

Image enter image description here

If it helps at all, the departmentID is a primary key. so departmentID 1 will always point to the same name and so on.

4

1 回答 1

5

您可以使用IEqualityComparer

class MyComparer<T> : IEqualityComparer<T> where T : SelectListItem
{
    public bool Equals(T x, T y)
    {
        return x.Value == y.Value ;
    }

    public int GetHashCode(T obj)
    {
        return obj.Id.GetHashCode();
    }
}

然后你的代码

ViewBag.DepartmentList = docs.Select(m => new SelectListItem
        {
            Value = SqlFunctions.StringConvert((double)m.departmentID).Trim(),
            Text = m.departmentName
        })
        .Distinct(new MyComparer<SelectListItem>()).ToList();
于 2013-05-14T16:46:58.290 回答