0

我将以下数据绑定到下拉列表,但无法获得不同的值。请帮忙。找到下面的代码片段

var SalesOrgTypes = (from s in tblSales
                         orderby s.SalesOrg ascending
                         select new DropDownItem
                         {
                             Value = s.SalesOrg,
                             Text = s.SalesOrg + " - " + s.SalesOrgDesc
                         }).Distinct();
4

1 回答 1

2

Distinct()正在使用定义的Equals(object obj)方法DropDownItem。您必须定义一个适当的IEqualityComparer并将其赋予Distinct(IEqualityComparer<T>)方法以告诉Distinct不要使用本机Equals(object obj)方法,而是使用您自己的均衡。

class DropDownItemEqualityComparer : IEqualityComparer<DropDownItem>
{
    #region IEqualityComparer<DropDownItem> Member

    public bool Equals(DropDownItem x, DropDownItem y)
    {
        return
            x == null || y == null 
            ? false
            : x.Value == y.Value && x.Text == y.Text; 
        //Or whatever properties you want to be equal
    }

    public int GetHashCode(DropDownItem obj)
    {
        if (obj != null)
            return
                obj.Value.GetHashCode() + obj.Text.GetHashCode();
        else
            throw new ArgumentNullException("obj");
    }

    #endregion
}

然后你可以把这个给Distinct方法

var SalesOrgTypes = (from s in tblSales
                         orderby s.SalesOrg ascending
                         select new DropDownItem
                         {
                             Value = s.SalesOrg,
                             Text = s.SalesOrg + " - " + s.SalesOrgDesc
                         }).Distinct(new DropDownItemEqualityComparer());
于 2012-10-12T12:34:44.400 回答