I remember seeing a question on here about the same problem, where things like:
if( x==null || x==" " || x==" " || x=="\n")...
End up becoming long and ugly strings, but the answer wasn't great and I can't remember what it was.
I'm in the middle of a tutorial on MySQL, and the way the problem is solved in SQL is by using the keyword "IN".
WHERE value IN (1 , 22, 35)...
So I was wondering if it's considered inefficient or bad practice to do:
object[] BadVals = {null, " ", " ", "\n"};
if(Array.IndexOf(BadVals, x) != -1)...
It's certainly not efficient in theory as the straight if
test, but this is a red herring. The real question is: do you care?
There's two sides to this question.
As for the LINQ approach, that's slightly shorter and a bit more readable than what you have:
if((new[] { null, " ", " ", "\n" }).Contains(x)) ...
You 'd probably want to write another extension method that allows you to call this with the operand positions reversed, e.g.
if(x.In(new[] { null, " ", " ", "\n" })) ...
Verdict: I 'd go with LINQ for more than 3 or so values to test against, provided that there's no other more obvious way to check for these values (e.g. in this case IsNullOrWhiteSpace
is awfully close) and there are no obvious performance implications. Otherwise, if
is tried and true.
Not necessarily bad practice, but there are some other ways. A couple of different ways are:
For null/empty Strings,
String.IsNullOrEmpty(s.Trim());
IsNullOrWhiteSpace
in 4.0:
String.IsNullOrWhitespace(s.Trim());
for an operator like SQL IN
:
if((new[] {" ", " ", "\n"}).Contains(s))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With