问题描述
我有自定义对象的强类型列表中,MyObject的,其中有一个属性标识与其他属性一起。
比方说,一个为MyObject的ID定义它作为独特的,我想检查我的收藏还没有一个具有标识1之前,我想补充我的新MyObject来的集合MyObject的对象。
我想用,如果(!List.Contains(MyObj中)),但我怎么执行的事实,只有一MyObject来的两个属性把它定义为独特之处?
我可以使用IComparable的?或者,我只有重写的equals方法,但我需要先继承的东西是吗?
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 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.
I want to use if(!List.Contains(myObj)) but how do I enforce the fact that only one or two properties of MyObject define it as unique?
I can use IComparable? Or do I only have to override an Equals method but I'd need to inherit something first is that right?
感谢
推荐答案
列表< T>。载
使用 EqualityComparer< T> .DEFAULT
,从而使用 IEquatable< T>
如果类型实现它,或者的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< T>
但它是一个好主意,覆盖的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()用来检查现有的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!