Find an item inside a List<T> by providing a sample object instance

mare picture mare · Aug 15, 2011 · Viewed 11.8k times · Source

Why is there a List<T>.Contains(T) method but no List<T>.Find(T) method? Only the Finds that support predicates are supported. If we have an existing instance of T populated with a property value for its ID (but missing other properties) why can't we search by providing this object instance to the search in List, especially when we have implemented custom IEquatable<T> for T and would like to use what's there. But as it is, we can't, we have to repeat everything that we did in IEquatable implementation in our Find(predicate) call.

Answer

Joel B Fant picture Joel B Fant · Aug 15, 2011

You can call the IEquatable<T> member(s) in your Predicate<T>. Then you won't be repeating yourself.

MyClass a = new MyClass(); //sample for finding; IEquatable<MyClass>
List<MyClass> list = GetInstances();

MyClass found = list.Find( mc => mc.Equals(a) );