简体   繁体   English

如何比较字符串和布尔数组?

[英]How can I compare a string and a bool array?

I have two arrays as below: 我有两个数组,如下所示:

_user string[3] containing "true" "true" and "true"
_test  bool[3] containing true true false

The number of elements in the arrays will vary from one run to another. 阵列中元素的数量会因一次运行而异。 My question is how can I compare the values in these two arrays and return true if the elements match one for one. 我的问题是如何比较这两个数组中的值,如果元素一对一匹配,则返回true。

Hope someone can help as my C# is not very good at all. 希望有人可以帮忙,因为我的C#根本不是很好。

Janet 珍妮特

Use bool.Parse to convert the strings to bool, and SequenceEqual to compare the sequences: 使用bool.Parse将字符串转换为bool,然后使用SequenceEqual比较序列:

if (_user.Select(bool.Parse).SequenceEqual(_test))
{
    ...
}
       bool equal=true;  
       for(int i=0;i<3;i++)
        {
         if (!( _user[i].equals(Convert.ToString(_test[i]))))
         {
             equal=false;
             break; 
         }

        }

or 要么

 equal=true;  
 for(int i=0;i<3;i++)
            {
              if !(_test[i]==Convert.ToBoolean(_user[i])))
                  {
                     equal=false;
                     break;
                  } 

        }

Not the LINQiest but the imperative solution is pretty clear in this case: 在这种情况下,不是LINQiest,但命令式解决方案非常清楚:

bool TestItems() {
  for (int i = 0; i < Math.Min(_user.Length, _test.Length); i++) {
    if (_test[i] != (_user[i] == "true")) {
      return false;
    }
  }
  return true;
}

It should be noted without any clarification in the question that this assumes both are the same length and that uneven array lengths will ignore the elements out of bounds of the smaller array. 应该指出的是,该问题假设两个长度都相同,并且不均匀的数组长度将忽略较小数组中超出范围的元素。

            bool [] array1 = {true,false, true};
            bool[] array2 = { true, true, true };
            bool result = false;
            for (int index = 0; index < array1.Length && index < array2.Length; index++)
            { 
                result = CheckTrueOrNot(array1[index],array2[index]);
                Console.WriteLine(result.ToString());
            }

        private bool CheckTrueOrNot(bool value1, bool value2)
        {
            bool comparisonVal = false;
            if (value1.CompareTo(value2) == 0)
            {
                comparisonVal = true;
            }

            return comparisonVal;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM