Link to home
Start Free TrialLog in
Avatar of coolrazor
coolrazor

asked on

Need an If statement to match text within any part of an array

This is what I have and it works, but there must be an easier way:

            string[] aSharpKey = { "A#", "B#", "C##", "D#", "E#", "F##", "G##", "A#" };
            string User1 = UserChord1.Text;

            if (aSharpKey[0] == User1 || aSharpKey[1] == User1 || aSharpKey[2] == User1 || aSharpKey[3] == User1 || aSharpKey[4] == User1 || aSharpKey[5] == User1 || aSharpKey[6] == User1 || aSharpKey[7] == User1)
{
 //stuff
}

Is there syntax for searching the array to match any element, like:  if(aSharpKey[0 thru 7] == User1)
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image


string[] aSharpKey = { "A#", "B#", "C##", "D#", "E#", "F##", "G##", "A#" };
string User1 = UserChord1.Text;
string found = Array.Find(aSharpKeyUser1);

if (found == User1 )
{
 //stuff
}
Find() is new in .Net 2.0.

You can also use the old IndexOf() method:
http://msdn2.microsoft.com/en-US/library/7eddebat(VS.80).aspx

Avatar of coolrazor
coolrazor

ASKER

I want to avoid using .Net 2.0
If possible, I'd like to avoid adding more strings or arrays before the "if" unless it simplifies this problem a lot.

Here's my latest try:

            string[] aSharpKey = { "A#", "B#", "C##", "D#", "E#", "F##", "G##", "A#" };
            string User1 = UserChord1.Text;

if (User1 == Array.IndexOf(aSharpKey, User1) )  //Error      1      Operator '==' cannot be applied to operands of type 'string' and 'int'
{
//stuff
}
I'll bite the bullet and use .Net if it'll make my life way easier, but the syntax below didn't work:

string[] aSharpKey = { "A#", "B#", "C##", "D#", "E#", "F##", "G##", "A#" };
string User1 = UserChord1.Text;
string found = Array.Find(aSharpKeyUser1); // the part inside the ( ) isn't right; I tried dots, commas, string, etc.  What's missing?

if (found == User1 )
{
 //stuff
}
Should be something like...

    int index = Array.Find(aSharpKey, User1);
    if (index != -1)
    {
        // "index" is the index it was found out
    }
    else
    {
        // the value was not found in the array
    }
Sorry...that should read:

    // "index" is the index it was found AT
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
I finally went Zephyr's approach, but had to add a little in the begining:

if(System.Collections.ArrayList.Adapter(aSharpKey).Contains(User1))  
{
//Stuff
}