[英]Getting distinct items for a list of address objects from stored procedure
So I am trying to get unique addresses only from my list but for some reason the .Distinct is not working 因此,我试图仅从列表中获取唯一地址,但由于某种原因,.Distinct无法正常工作
I tried : 我试过了 :
List<Address> addresses = _db.Database.SqlQuery<Address>(
"GetSampleAddresses @workflow_id, @records ", param1, param2).Distinct().ToList();
And 和
var json = new JavaScriptSerializer().Serialize(addresses.Distinct());
But neither removes the duplicates, any idea why ? 但是都没有删除重复项,为什么?
The thing is that when you're using .Disctinct()
overload without parameters it will compare objects on reference base (by using by using the default equality comparer). 事实是,当您使用不带参数的
.Disctinct()
重载时,它将在引用基础上比较对象(通过使用默认的相等比较器进行比较)。 Other words same object added twice to your collection will be treated as duplication, but two different objects with same fields/properties won't be equal. 换句话说,两次被添加到您的集合中的同一个对象将被视为重复对象,但是具有相同字段/属性的两个不同对象将不相等。
To compare by specific fields you'll have to provide IEqualityComparer
which will do a comparison: 要按特定字段进行比较,您必须提供
IEqualityComparer
进行比较:
var json = new JavaScriptSerializer().Serialize(addresses.Distinct(new AddressComparer()));
And AddressComparer
itself: 和
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.