views:

136

answers:

7

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?

+2  A: 

Enumerable.Contains if you're using C# 3.0 or later.

e.g.

var contained = myArray.Contains(4);
Greg Beech
+1  A: 
var myArray = new []  { 1, 2};
if myArray.Contains(1)
{
do something
}

You may need a using System.Linq;

Kindness,

Dan

Daniel Elliott
+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
+1  A: 

You could use the IndexOf method:

int[] array = new int[] { 1, 2, 3 };
bool isArrayContains17 = Array.IndexOf(array, 17) > -1;
Darin Dimitrov
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
Binary search only works if array is sorted
yu_sha
And you vote my comment down based on this?
Mick Walker
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
+3  A: 

The Enumerable.Contains() Method is your friend in .NET-Framework 3.5...

EricSchaefer
Providing you are using .NET 3.5
RichardOD
@RichardOD: You are right. Editing the answer...
EricSchaefer
+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
This new Contains method is not well publicized.
I. J. Kennedy