如何将数组与用户输入进行比较并查看它是否匹配?

时间:2016-12-01 00:48:51

标签: c# arrays

 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();

我需要做的就是在用户输入选项后搜索这个数组,如果他们的输入不在数组中,则循环返回并要求他们重新输入数据。

如果没有使用数组有更好的方法,也欢迎使用该选项。

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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
}

答案 1 :(得分:2)

如果您只是寻找有效的月份名称,您可以这样做:

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

答案 2 :(得分:1)

HashSet<string>是最好的选择,速度快,不需要重复。

StringComparer.OrdinalIgnoreCase会使其不区分大小写。

HashSet方法

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");

数组方法

但是,如果您仍想在阵列上执行此操作,则可以进行比较:

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

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