Search an Array

How do I manually search an array for an exact match in C#?
NikkitaKMilesAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ravi SinghSenior Software EngineerCommented:
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...
NikkitaKMilesAuthor Commented:
its of type int.  
Ravi SinghSenior Software EngineerCommented:
Ok small modification:

int[] array = new int[ size ]; //your int array

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ravi SinghSenior Software EngineerCommented:
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.
NikkitaKMilesAuthor Commented:
Thanks,

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

Nikkita
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.