簡體   English   中英

如何比較字符串和布爾數組?

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

我有兩個數組,如下所示:

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

陣列中元素的數量會因一次運行而異。 我的問題是如何比較這兩個數組中的值,如果元素一對一匹配,則返回true。

希望有人可以幫忙,因為我的C#根本不是很好。

珍妮特

使用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; 
         }

        }

要么

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

        }

在這種情況下,不是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;
}

應該指出的是,該問題假設兩個長度都相同,並且不均勻的數組長度將忽略較小數組中超出范圍的元素。

            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