What does Collection.Contains() use to check for existing objects?

前端 未结 6 1175
眼角桃花
眼角桃花 2020-12-03 09:34

I have a strongly typed list of custom objects, MyObject, which has a property Id, along with some other properties.

Let\'s say that the

6条回答
  •  囚心锁ツ
    2020-12-03 10:02

    List.Contains uses EqualityComparer.Default, which in turn uses IEquatable if the type implements it, or object.Equals otherwise.

    You could just implement IEquatable but it's a good idea to override object.Equals if you do so, and a very good idea to override GetHashCode() if you do that:

    public class SomeIDdClass : IEquatable
    {
        private readonly int _id;
        public SomeIDdClass(int id)
        {
            _id = id;
        }
        public int Id
        {
            get { return _id; }
        }
        public bool Equals(SomeIDdClass other)
        {
            return null != other && _id == other._id;
        }
        public override bool Equals(object obj)
        {
            return Equals(obj as SomeIDdClass);
        }
        public override int GetHashCode()
        {
            return _id;
        }
    }
    

    Note that the hash code relates to the criteria for equality. This is vital.

    This also makes it applicable for any other case where equality, as defined by having the same ID, is useful. If you have a one-of requirement to check if a list has such an object, then I'd probably suggest just doing:

    return someList.Any(item => item.Id == cmpItem.Id);
    

提交回复
热议问题