I have an array of a certain type. Now I want to find an entry where a certain condition is met.
What is the preferred way to do this with the restriction that I don’t want to create a temporary object to find, but instead I only want to give a search condition.
MyClass[] myArray;
// fill and sort array..
MyClass item = Array.BinarySearch(myArray, x=>x.Name=="Joe"); // is this possible?
Maybe is it possible to use LINQ to solve it?
EDIT:
I know that it works on normal collections, but I need it to work for BinarySearch.
Just use FirstOrDefault (or SingleOrDefault, if unique).
Or if you want to force a BinarySearch and you know that the array is sorted
where MyClassNameComparer is
IComparer<MyClass>and compares based on the name property.If you don’t want any temporary object — I assume that a constant string is ok, otherwise you’re lost — then you can use.
Where MyClassOrStringComparer is able to compare a string to a MyClass object (and vice versa).