Reputation: 19
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
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<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");
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
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
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