Find an item inside a List<T> by providing a sample object instance
-
23-12-2020 - |
Question
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.
Solution
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) );
OTHER TIPS
how about this
list.Any(i => i.ID == searchObj.ID);
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.