If I have an array of ints, and I want to quickly check if a certain int value is in that array, is there a method to do that?
If the array is sorted, then this is quickest:
Array.BinarySearch(myArray, value) >= 0;
If the array is searched a lot and rarely modified, then you may find it worthwhile to sort the array after modification (using Array.Sort) and use the above. Otherwise, use the option you prefer:
Array.IndexOf(myArray, value) >= 0; //.Net 1
Array.Exists(array, delegate(int x) { return x == value; }); //.Net 2
myArray.Contains(value); //.Net 3
IndexOf has the best performance for unsorted arrays. The second option uses a predicate delegate, and the third requires the creation of an enumerator object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With