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

前端 未结 6 1173
眼角桃花
眼角桃花 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:20

    List uses the comparer returned by EqualityComparer.Default and according to the documentation for that:

    The Default property checks whether type T implements the System.IEquatable(Of T) interface and, if so, returns an EqualityComparer(Of T) that uses that implementation. Otherwise, it returns an EqualityComparer(Of T) that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

    So you can either implement IEquatable on your custom class, or override the Equals (and GetHashCode) methods to do the comparison by the properties you require. Alternatively you could use linq:

    bool contains = list.Any(i => i.Id == obj.Id);
    

提交回复
热议问题