简体   繁体   中英

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.

Basically I'm trying to check if list contains X in any second indices.

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.

Here is a sample IEqualityComparer<Entity.Limit> implementation

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.

using System.Linq;
...
bool contains = list.Contains(
  new Entity.Limit(1, 2),
  new EntityEqualityComparer());

Have Entity.Limit override 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM