Collection.Contains() 使用什么来检查现有对象? [英] What does Collection.Contains() use to check for existing objects?

查看:16
本文介绍了Collection.Contains() 使用什么来检查现有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个强类型的自定义对象列表,MyObject,它有一个属性 Id,以及一些其他属性.

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

假设 MyObjectId 将其定义为唯一的,我想检查我的集合是否还没有 MyObject 在我将新的 MyObject 添加到集合之前,Id 为 1 的对象.

Let's say that the Id of a MyObject defines it as unique and I want to check if my collection doesn't already have a MyObject object that has an Id of 1 before I add my new MyObject to the collection.

我想使用 if(!List<MyObject>.Contains(myObj)),但是我如何强制执行只有 MyObject 的一两个属性的事实将其定义为唯一?

I want to use if(!List<MyObject>.Contains(myObj)), but how do I enforce the fact that only one or two properties of MyObject define it as unique?

我可以使用 IComparable 吗?还是我只需要覆盖一个 Equals 方法?如果是这样,我需要先继承一些东西,对吗?

I can use IComparable? Or do I only have to override an Equals method? If so, I'd need to inherit something first, is that right?

推荐答案

List.Contains 使用 EqualityComparer.Default,而EqualityComparer.Default 又使用 IEquatable 如果类型实现它,或者 object.Equals 否则.

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

您可以只实现 IEquatable 但如果这样做,最好覆盖 object.Equals,并且非常如果你这样做,覆盖 GetHashCode() 的好主意:

You could just implement IEquatable<T> 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<SomeIDdClass>
{
    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.

这也使它适用于任何其他情况,其中通过具有相同 ID 定义的相等性很有用.如果您有一个要求来检查列表是否有这样的对象,那么我可能建议您这样做:

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);

这篇关于Collection.Contains() 使用什么来检查现有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆