What does Collection.Contains() use to check for existing objects?
You can use LINQ to do this pretty easily.
var result = MyCollection.Any(p=>p.myId == Id);
if(result)
{
//something
}
List<T>
uses the comparer returned by EqualityComparer<T>.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<T>
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);
List<T>.Contains
uses EqualityComparer<T>.Default
, which in turn uses IEquatable<T>
if the type implements it, or object.Equals
otherwise.
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.
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);
You can override Equals and GetHashCode, implement an IEqualityComparer<MyObject>
and use that in the Contains
call, or use an extension method like Any
if (!myList.Any(obj => obj.Property == obj2.Property && obj.Property2 == obj2.Property2))
myList.Add(obj2);