Check if an array contains an invalid value and return false?
This is probably very simple but I guess I haven't had enough of coffee yet.
I have an array开发者_运维技巧 with four values and I want to check if any of them is invalid and then set a boolean value to false, else to true.
bool validDecoding = false;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
}
else
{
validDecoding = true;
}
}
But if the last does not contain invalid, length or bad then validDecoding is set to true but I want it to be false if one or more values are invalid.
Please help?
Thanks in advance.
Include System.Linq
namespace and you can do following:
validDecoding = !arrayOfvalues.Any(
value => value.Contains("invalid") || value.Contains("length") || value.Contains("bad"));
bool validDecoding = false;
foreach (string decodedValue in arrayOfvalues)
{
if (!decodedValue.Contains("invalid") && !decodedValue.Contains("length") && !decodedValue.Contains("bad"))
{
validDecoding = true;
break;
}
}
Set valid to true at first, then set it to false in your loop if it's invalid.
bool validDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
break;
}
}
That way it's never set back to true! (you need more coffee ;-) )
Set your validDecoding to 'true' initially, and only reset to false if it breaks.
bool validDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
if (decodedValue.Contains("invalid") || decodedValue.Contains("length") || decodedValue.Contains("bad"))
{
validDecoding = false;
}
else
{
//Do Nothing
}
}
I like Andrew's answer. If you don't have Linq available, try this option:
// Note: Name boolean variables like they are a question
bool isValidDecoding = true;
foreach (string decodedValue in arrayOfvalues)
{
isValidDecoding &= !decodedValue.Contains("invalid")
&& !decodedValue.Contains("length")
&& !decodedValue.Contains("bad");
}
I particularly like this option when your tests contain logging, and you want to find all failures before termination.
I'd be wary of decodedValue.Contains("length")
though. Maybe it works in your scenario, but it might give false negatives for other cases, and definitely makes your code less clear. You should double check that there isn't a more unique/indicative value that ensures that you have a bad decoding for those cases.
精彩评论