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?
+1
A:
var myArray = new [] { 1, 2};
if myArray.Contains(1)
{
do something
}
You may need a using System.Linq;
Kindness,
Dan
Daniel Elliott
2009-11-27 08:48:02
+4
A:
Use for example this, if you want to check if your array contains the int 0:
if (your_int_array.Contains(0))
{
//Code
}
Maximilian Mayerl
2009-11-27 08:48:16
+1
A:
You could use the IndexOf method:
int[] array = new int[] { 1, 2, 3 };
bool isArrayContains17 = Array.IndexOf(array, 17) > -1;
Darin Dimitrov
2009-11-27 08:48:29
A:
Try this function:
public static bool FindValueFromArray(object[] Values,object valueToSearch){
bool retVal = false;
Array myArray = (Array)Values;
int found = Array.BinarySearch(myArray, valueToSearch);
if (found != -1){
retVal = true;
}
return retVal;
}
Hope this helps.
Mick Walker
2009-11-27 08:49:04
Binary search only works if array is sorted
yu_sha
2009-11-27 08:58:10
And you vote my comment down based on this?
Mick Walker
2009-11-27 09:00:30
I've +1. But I'd add that sorting is required and it is only really worth it if you are doing repeated searches.
RichardOD
2009-11-27 09:05:51
+3
A:
The Enumerable.Contains() Method is your friend in .NET-Framework 3.5...
EricSchaefer
2009-11-27 08:49:40
+8
A:
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.
Matt Howells
2009-11-27 09:24:07