在linq mvc3中选择不同的值

时间:2012-10-12 12:24:52

标签: asp.net-mvc-3 linq

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

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

1 个答案:

答案 0 :(得分: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());