所以我试图仅从我的列表中获取唯一地址但由于某种原因,.Distinct无法正常工作
我试过了:
List<Address> addresses = _db.Database.SqlQuery<Address>(
"GetSampleAddresses @workflow_id, @records ", param1, param2).Distinct().ToList();
并且
var json = new JavaScriptSerializer().Serialize(addresses.Distinct());
但是既没有删除重复,也不知道为什么?
答案 0 :(得分:1)
问题在于,当您使用.Disctinct()
重载而没有参数时,它将比较参考基础上的对象(通过使用默认的相等比较器)。换句话说,将两次添加到您的集合中的相同对象将被视为重复,但具有相同字段/属性的两个不同对象将不相等。
要按特定字段进行比较,您必须提供IEqualityComparer
进行比较:
var json = new JavaScriptSerializer().Serialize(addresses.Distinct(new AddressComparer()));
AddressComparer
本身:
class AddressComparer: IEqualityComparer<Address>
{
public bool Equals(Address x, Address 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;
// Compare properties here.
// Assuming that two Addresses are equal when Street and Code are equal.
return x.Street == y.Street && x.Code == y.Code;
}
// If two objects are equal GetHashCode for both should return same value.
public int GetHashCode(Address address)
{
if (Object.ReferenceEquals(address, null))
return 0;
int hashAddress = address.Street == null ? 0 : address.Street.GetHashCode();
int hashCode = address.Code.GetHashCode();
// Calculate new hash code from unique values combinaiton.
return hashAddress ^ hashCode;
}
}