如何将一个固定值与多个值进行比较,并找出是否有任何一个不匹配

How to compare a fixed value against multiple values and find if any one fails to match

我有一个固定的 int 值 - 1050。我有大约 50 个动态值要与固定值进行比较。所以我在for循环中比较它。我有一个 public 变量,我根据结果将其设置为 ok 或 notok。但我的问题是 public 变量的值始终是我比较的最后一个值。例如,如果我将第 20 个动态值设置为 1000,它应该 return notok,但变量的值始终是最后比较的值。即使 one/multiple 的动态变量值与固定变量不匹配,如何将变量设置为 notok?我还在列表框中显示了 notok 值的总数。

这是我的资料:

  string result;
  for(int i = 0; i < dynamicvalue.count; i++)
  {
    if(dynamicvalue[i] != setvalue)
    {
        result = "notok";
        listBox1.Items.Add(result);
    }
    else
    {
        result = "ok";
    }
   }

您忘记获取 dynamicvalue 内的实际值:您的测试应该是 if (dynamicvalue[i] != setvalue)

编辑:并在 result="ok"; 指令后添加一个 break; 来打破循环。

编辑 2:上面的答案使用 break.

给出了更正后的代码

您可以使用 Linq 中的 .Any()

Determines whether any element of a sequence exists or satisfies a condition.

string result =  dynamicvalue.Any(x => x == setValue) ? "Ok" : "Not Ok";

如果您想在没有 break 语句的情况下使用 for 循环,您只会增加代码的时间复杂度。

我永远不会推荐它,但如果你愿意,可以试试下面的代码

string result = "Ok";
bool flag = true;
//This for loop will iterate for n times.
for(int i = 0; i < dynamicvalue.Count; i++)
{
  if(dynamicvalue[i] != setvalue && flag)
     {
      result = "Not Ok";
      flag = false;   //flag will help us to execute this block of code only once.
     }
 }

"notok" 如果至少有一个不匹配,一种用明码实现的方法:

string result = "ok";
for(int i=0; i<dynamicvalue.count; ++i)
    {
      if(dynamicvalue[i] != setvalue)
         {
          result = "notok";
          break;
         }
     }

也许回答这个问题的最有效方法是将您的数字保存在 HashSet 中(使 dynamicvalue 成为 HashSet<int>),然后是:

dynamicvalue.Contains(setvalue) ? "ok" : "notok"

HashSet 可以更快地回答“你包含这个值吗?”比 list/array 可以

根据评论中进行的讨论,我认为您想遍历 dynamicvalue 中的所有元素并检查所有元素是否正常。如果是这种情况,您应该将 result 转换为数组。您会得到最后一个比较结果,因为每次循环循环时,字符串都会重新分配一个新值,因此先前的值会被丢弃。

这是你想做的吗?我用c++写的

  int setvalue = 1050;
  int notok = 0;
  int dynamicvalue[5] = {1, 2, 3, 1050, 4}; //for example
  string result[5];
  for (int i = 0; i < sizeof(dynamicvalue); i++){
    if (dynamicvalue[i] != setvalue){
      result[i] = "notok";
      notok++; //to keep track of notok
    }
    else{
      result[i] = "ok";
    }
  }

之后,如果您循环浏览结果数组,您将看到所有值都已保存。我发现有一个 int 变量来知道结果是 notok

的次数更简单

我通过阅读@deminalla 的回答找到了解决这个问题的方法。

我又添加了两个整数作为计数器,在 for 循环之后我比较了这些整数的值以获得最终结果。

这是我所做的:

 string result;
 int okcounter = 0;
 int notokcounter = 0;
 for(int i = 0; i < dynamicvalue.count; i++)
 {
   if(dynamicvalue[i] != setvalue)
   {
     notokcounter ++;
     listBox1.Items.Add(notokcounter);
   }
   else
   {
     okcounter++;;
   }
 }
 if(notokcounter >=1)
 {
   result = "notok";
 }
 else if(okcounter == dynamicvalue.count)
 {
   result = "ok";
 }