Link to home
Start Free TrialLog in
Avatar of NikkitaKMiles
NikkitaKMiles

asked on

Search an Array

How do I manually search an array for an exact match in C#?
Avatar of Ravi Singh
Ravi Singh
Flag of United Kingdom of Great Britain and Northern Ireland image

Hi, whats the arrays type? If its a string array you could try:

string[] array = new string [ size ];

for (int i = 0; i < array.Length; i++)
{
       if (array[i] == MyOtherString)
       {
            //Match found
            break; //breaks out of the for loop
       }
}

If its not a string you could compare properties of the two objects etc...
Avatar of NikkitaKMiles
NikkitaKMiles

ASKER

its of type int.  
ASKER CERTIFIED SOLUTION
Avatar of Ravi Singh
Ravi Singh
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Alternatively you could use the Array.BinarySearch(...) method:

int[] array = {1, 2, 3}; //Your int array
int position = Array.BinarySearch(array, 0, array.Length, 2);

First parameter is the array to search, second is the starting index for the search, 3rd is the length of the array to search and the final parameter is the integer your searching for.

The position variable holds the index of the matching int in your array.
Thanks,

I understand the concept and got my code to working.  Good Job!!!!!!!

Nikkita