Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a value is in an array in Visual C#

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?

like image 267
neuromancer Avatar asked Dec 30 '25 07:12

neuromancer


1 Answers

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.

like image 171
Matt Howells Avatar answered Jan 01 '26 20:01

Matt Howells