How to find if a value is in an array in Visual C#
.net, arrays, c#, search, visual-studio
Solution
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.
Problem
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?