Inderbir
Inderbir

Reputation: 19

How can I compare an array with users input and see if it matches?

 string[] array = { "January", "january", "February", "february", "March", "march", "April", "april", "May", "may", "June", "june",
        "July", "july", "August", "august", "Sepetember", "september", "October", "october", "November", "november", "December", "december"};


Console.Write("\nWhat month will this event be taking place? ");
sMonth = Console.ReadLine();

All I need to do is search through this array after the user has inputted their option, and if their input isn't within the array, loop back and ask them to re-input the data.

If there's a better way without using an array, that option is welcome too.

Upvotes: 0

Views: 85

Answers (3)

Jim
Jim

Reputation: 2984

HashSet<string> is the best option, it's fast and no duplicates to make.

The StringComparer.OrdinalIgnoreCase will make it case insensitive.

HashSet method

HashSet<string> months = new HashSet<string>(StringComparer.OrdinalIgnoreCase)            
{
    "January" ,"February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
};

Console.Write("\nWhat month will this event be taking place? ");
string sMonth = Console.ReadLine();

while (!months.Contains(sMonth))
{
    Console.WriteLine("The month was invalid, retry ...");
    sMonth = Console.ReadLine();
}

Console.WriteLine("Valid ... lets do other stuff");

Array method

However, if you still want to do this on an array, you can compare like so:

while (!Array.Exists(array, m => m == sMonth))
{
    Console.WriteLine("The month was invalid, retry ...");
    sMonth = Console.ReadLine();
}

Console.WriteLine("Valid ... lets do other stuff");

Upvotes: 1

D Stanley
D Stanley

Reputation: 152511

If you are just looking for a valid month name you can do:

bool isValid = DateTime.TryParseExact(monthName, "MMMM", CultureInfo.InvariantCulture );

Upvotes: 2

Abion47
Abion47

Reputation: 24626

You can achieve this like so:

HashSet<string> set = new HashSet<string> { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" };

Console.Write("\nWhat month will this event be taking place? ");
sMonth = Console.ReadLine();

if (!set.Contains(sMonth.ToLower()))
{
    // Re-prompt for month
}

Upvotes: 3

Related Questions