Reputation: 23
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.
Hope someone can help as my C# is not very good at all.
Janet
Upvotes: 1
Views: 272
Reputation: 2154
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;
}
Upvotes: 0
Reputation: 570
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;
}
}
Upvotes: 1
Reputation: 10074
Not the LINQiest but the imperative solution is pretty clear in this case:
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.
Upvotes: 0
Reputation: 292465
Use bool.Parse
to convert the strings to bool, and SequenceEqual
to compare the sequences:
if (_user.Select(bool.Parse).SequenceEqual(_test))
{
...
}
Upvotes: 13