array.exist help

R

rodchar

hey all,

string[] validOptions = { "1", "2", "3", "4", "e" };

if (Array.Exists<string>(validOptions, delegate(string s) {
return s.Contains(userInput);}))
{

Console.WriteLine("Thanks for the valid option.");
Console.ReadKey();
return true;
}

when a user just presses Enter without typing in anything it is considered a
valid option when in fact string.empty is not in the list. Any ideas?

thanks,
rodchar
 
T

Tom P.

hey all,

            string[] validOptions =  { "1", "2", "3", "4", "e" };            

            if (Array.Exists<string>(validOptions, delegate(string s) {
return s.Contains(userInput);}))
            {

                Console.WriteLine("Thanks for the valid option.");
                Console.ReadKey();
                return true;
            }

when a user just presses Enter without typing in anything it is considered a
valid option when in fact string.empty is not in the list. Any ideas?

thanks,
rodchar

All strings Contain empty space, therefore if you look for empty space
in a string you will find it. And if you null out the userInput you
will get a Null Object Reference error.

Best suggestion I can think of is to check expressly for
String.IsNullOrEmpty() and return to the input method. Then, if the
input gets past that check you can see if the input is one of the
actual choices.

Tom P.
 
P

Patrice

Hi,

Likely because the empty string is contained into all those strings... I
believe what you want is to find out an array entry that is *equal* to the
user input not that *contains* the user input...
 
R

rodchar

thanks for the help"o wise one" :)
rod.

Patrice said:
Hi,

Likely because the empty string is contained into all those strings... I
believe what you want is to find out an array entry that is *equal* to the
user input not that *contains* the user input...

--
Patrice

rodchar said:
hey all,

string[] validOptions = { "1", "2", "3", "4", "e" };

if (Array.Exists<string>(validOptions, delegate(string s) {
return s.Contains(userInput);}))
{

Console.WriteLine("Thanks for the valid option.");
Console.ReadKey();
return true;
}

when a user just presses Enter without typing in anything it is considered
a
valid option when in fact string.empty is not in the list. Any ideas?

thanks,
rodchar
 
B

Ben Voigt [C++ MVP]

rodchar said:
hey all,

string[] validOptions = { "1", "2", "3", "4", "e" };

if (Array.Exists<string>(validOptions, delegate(string s) {
return s.Contains(userInput);}))
{

Console.WriteLine("Thanks for the valid option.");
Console.ReadKey();
return true;
}

A predicate is overkill for what you're doing. Use

Array.IndexOf(validOptions, userInput) >= 0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top