C#: is there a method to see if an array contains a certain object?

KB

Diamond Member
Nov 8, 1999
5,406
389
126
There are two methods of the array object that may help:

BinarySearch
Supported by the .NET Compact Framework.
Overloaded. Searches a one-dimensional sorted Array for a value, using a binary search algorithm.

LastIndexOf
Supported by the .NET Compact Framework.
Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.

If this is a custom object you may have to override the Equals method so the comparison can take place.
I would still use a for loop as it is guaranteed to work.
 

torpid

Lifer
Sep 14, 2003
11,631
11
76
IndexOf and LastIndexOf won't work in all scenarios. If you have reference types it's just going to compare the references and not the values. BinarySearch will compare the values (and note you must implement IComparable) but you must sort the array first.