为什么LINQ中的区别对于这种情况不起作用?

时间:2012-01-22 09:36:54

标签: c# linq

我的对象Tenant

有这个比较器
public class TenantComparer : IEqualityComparer<Tenant>
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(Tenant x, Tenant y)
    {

        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the products' properties are equal.
        return x.Name == y.Name;
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(Tenant tenant)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(tenant, null)) return 0;

        //Get hash code for the Name field if it is not null.
        int hashProductName = tenant.Name == null ? 0 : tenant.Name.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName;
    }
}

现在,我有一个包含一些租户的表,其中一些具有相同的名称。我想按名称获取不同顺序的那些:

public static List<Tenant> GetTenantListOrderyByNameASC()
{
    DataClassesDataContext db = new DataClassesDataContext();
    var tenantsList = (from t in db.Tenants
                       select t).Distinct().OrderBy( x => x.Name ).ToList();

    return tenantsList;
}

但它仍然显示了同名的租户......

你能告诉我我哪里错了吗?

1 个答案:

答案 0 :(得分:5)

您需要明确提供比较器,此时您不需要:

var tenantsList = (from t in db.Tenants
                   select t)
    .Distinct(new TenantComparer())
    .OrderBy( x => x.Name )
    .ToList();

请参阅documentation