【问题标题】:How to compare a string value to an element of an string array in c#? [duplicate]如何在c#中将字符串值与字符串数组的元素进行比较? [复制]
【发布时间】:2020-02-01 17:43:21
【问题描述】:

在以下程序中,我想检查(通过防御编程)用户是否输入(命名日) 匹配字符串数组的元素之一(命名为 weekdays)。

到目前为止,我已经完成了以下操作。任何人都可以提供帮助(以获得更好的解决方案)吗?谢谢。

....

string[] weekdays = new string[7] { "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", "Sunday"};

      Console.WriteLine("Give me a day: ");
        String day= Console.ReadLine();


         for (i=0; i< weekdays.Length; i++)
        {
            if (weekdays[i] == day)
            {

                break;
            }
            else if (weekdays[i] != day && i==6)
            {
                Console.WriteLine("Try again");
                day = Console.ReadLine();
                i = -1;
            }
        }

【问题讨论】:

标签: c# arrays


【解决方案1】:

可以使用Linq.Any()函数:

using System.Linq;
...

string[] weekdays = new string[7] { "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday", "Sunday"};

Console.WriteLine("Give me a day: ");
String day= Console.ReadLine();

//No need to iterate over array and check day exists in array or not.
//You can use .Contains() method as well.
if(weekdays.Any(x => x == day))   
     break;
else
{
      Console.WriteLine("Try again");
      day = Console.ReadLine();
}

如果您希望它在循环中,那么您可以根据您的要求使用while(&lt;condition&gt;)for 循环

From MSDN:

Linq Any() 方法:判断一个序列的任何元素是否存在 或满足条件。


您可以使用以下逻辑来执行相同的操作,而无需任何 linq 功能和简化的解决方案:

//Week days array
string[] weekdays = new string[7] { "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday", "Sunday"};

//While infinity loop to execute inner code till incorrect day enters like "hey" 
while(true)
{
   //Read first input from user
   Console.WriteLine("Give me a day: ");
   string day= Console.ReadLine();

   //flag to check user entered correct value or not
   bool isAvailable = false;
   foreach(var wday in weekdays)
   { 
      //If entered day is correct then set flag and exit from foreach loop 
      if(wday == day)
      {
         isAvailable = true;
         break;
      }
   }
   //Check flag and if entered value is wrong then read user input again.
   if(isAvailable)
      break;
   else
   {
      Console.WriteLine("Try again");
      day = Console.ReadLine();
   }
} 

【讨论】:

  • 非常感谢您的建议。但是(如果可以的话)您能否向我解释一下它如何与 while 循环或 for(没有 .Any 函数)一起工作,我会很感激。再次感谢您!
  • 您想用 for 循环或 while 循环做什么,根据您的问题,您正在寻找更好的解决方案来检查 day 是否存在于任何数组中。这个答案满足。但我不明白你的 else 循环。如果用户输入的不是weekdays,是否要再次检查day
  • .Any() 函数(我在回答中已经提到)有几个替代方案,例如 .Contains().Exists() 等等。但你到底想做什么?你想在没有Linq 方法的情况下执行这个逻辑吗?
  • else 循环适用于用户输入除了像“hey”这样的元素之外还有其他值的情况
  • @NavyAlsk,查看我的最新更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多