[英]Check if List Contains() entity item
I have a entity list. 我有一个实体列表。 The entity has two integer variables. 该实体有两个整数变量。 I'm trying to check if the list contains that identity but it always returns false. 我正在尝试检查列表是否包含该身份,但它始终返回false。
Basically I'm trying to check if list contains X in any second indices. 基本上我想检查列表是否在任何第二个索引中包含X。
List<Entity.Limit> list = new List<Entity.Limit>();
list.Add(new Entity.Limit(1, 2));
list.Add(new Entity.Limit(1, 3));
list.Add(new Entity.Limit(1, 4));
Response.Write(list.Contains(new Entity.Limit(1, 2))); //Returns False
The problem here is that you are using reference based equality when really you want value based equality. 这里的问题是,当您真正想要基于价值的平等时,您正在使用基于引用的平等。 In order to get value equality you need to either pass an IEqualityComparer<T>
to the Contains
extension method which does the equality or override Equals
and GetHashCode
for the Equality.Limit
type. 为了获得值相等性,您需要将IEqualityComparer<T>
传递给Contains
相等性的Contains
扩展方法,或者为Equality.Limit
类型覆盖Equals
和GetHashCode
。
Here is a sample IEqualityComparer<Entity.Limit>
implementation 这是IEqualityComparer<Entity.Limit>
实现的示例
public sealed class EntityEqualityComparer : IEqualityComparer<Entity.Limit> {
public bool Equals(Entity.Limit left, Entity.Limit right) {
return
left.Value1 == right.Value1 &&
left.Value2 == right.Value2;
}
public int GetHashCode(Entity.Limit left) {
return left.Value1 ^ left.Value2;
}
}
Note: Replace Value1
and Value2
with the appropriate property names for the 2 values. 注意:将Value1
和Value2
替换为2个值的适当属性名称。
using System.Linq;
...
bool contains = list.Contains(
new Entity.Limit(1, 2),
new EntityEqualityComparer());
Have Entity.Limit
override Object.Equals
. 让Entity.Limit
覆盖Object.Equals
。 Right now, it's comparing references, and so not matching any of them. 现在,它正在比较参考,因此不匹配任何参考。 So: 所以:
class Limit {
// ...
public override bool Equals(object obj) {
Limit l = obj as Limit;
if(l != null) {
// Compare the two and return true if they are equal
}
return false;
}
}
Then Contains()
will be able to compare your objects properly. 然后Contains()
将能够正确比较您的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.