Why is there a List<T>.Contains(T)
method but no List<T>.Find(T)
method? Only the Find
s 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.
Asked
Active
Viewed 1.2k times
2

mare
- 13,033
- 24
- 102
- 191
-
2What is the use of a `Find(T)` method, when you already have that instance? That would be equivalent to the `Contains(T)` method, because the only thing the `Find(T)` will tell you is whether that list contains that instance. – Steven Aug 15 '11 at 14:40
-
1I imagine because he's trying to get a reference to the object in the list... just because he has an object that "equals" the other, especially considering that he implemented IEquatable and it's not just a reference comparison, that doesn't mean he's got a reference to the object he wants. – canon Aug 15 '11 at 14:46
-
exactly as antisanity puts it – mare Aug 15 '11 at 14:52
3 Answers
10
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) );

Joel B Fant
- 24,406
- 4
- 66
- 67
1
EDIT:
I think I understood your question now. You can use the List<T>.IndexOf
method for this purpose:
int index = myList.IndexOf(mySample);
if(index != -1)
{
var item = myList[index];
// Do something with item.
}
But this would be quite strange, because clearly, your equality definition isn't quite the whole picture - it's a bit of an abuse of equality, IMO.

Ani
- 111,048
- 26
- 262
- 307
-
MSDN: This method determines equality using the default equality comparer EqualityComparer
.Default for T. This method performs a linear search; therefore, this method is an O(n) operation – sll Aug 15 '11 at 14:49 -
My equality definition is just fine, it just says that two properties define the equality not just one. – mare Aug 15 '11 at 15:15