gpt4 book ai didi

c# - 为什么 distinct in LINQ 不适用于这种情况?

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:30 24 4
gpt4 key购买 nike

我的对象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;
}
}

现在,我有一张 table ,上面有一些租户,其中一些租户同名。我想按名称获取那些不同的顺序:

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;
}

但是还是显示同名的租户...

你能告诉我哪里错了吗?

最佳答案

您需要明确提供比较器,目前您不需要:

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

参见 documentation .

关于c# - 为什么 distinct in LINQ 不适用于这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com