views:

140

answers:

4

Hi there. I am currently struggling with about 5 nested if-statements and its becoming quite confusing to look over all of them.

So, I thought about adding ternary operators instead of ifs for simple checks, see

foreach (String control in controls)
{
 if (!control.Equals(String.Empty))
 {
   // Do some stuff
   foreach (Int32 someStuff in moreStuff)
   {
    if (!someStuff.Equals(0))
    {
     // More stuff with more if equals
    }
   }
 }

Thats how it looks like right now. Thats my idea on how to make it look a little bit more nice:

foreach (String control in controls)
{
 (control.Equals(String.Empty)) ? continue : null;
 // Do some stuff
 foreach (Int32 someStuff in moreStuff)
 {
  (someStuff.Equals(0)) ? continue : null;
  // More stuff
 }
}

So, the questions are: 1. is is bad programming to solve it like this and 2. will it work the way I want?

+3  A: 

Why don't you just do the following?

foreach (String control in controls)
{
 if(control.Equals(String.Empty))
      continue;
 // Do some stuff
 foreach (Int32 someStuff in moreStuff)
 {
  if(someStuff.Equals(0))
      continue;
  // More stuff
 }
}

Imho, its way more readable :)

x3ro
+2  A: 

No, that won't work at all. The conditional operator doesn't let you change flow control like that - it just evaluates either the second or third expression based on the first one. The result of the conditional expression is the result of whichever expression is evaluated (after any required conversions have been applied).

It's likely that LINQ will make your life considerably easier here, although you'd need to give a more complete example of what you want to do in order to make it clear.

EDIT: Just to give an alternative to Dave's answer:

var query = from control in controls
            where control != ""
            from someStuff in moreStuff
            where someStuff != 0
            select new { control, someStuff };

foreach (var result in query)
{
    // Do things with result.control and result.someStuff
}
Jon Skeet
+12  A: 

No it won't, the ternary operator has to have values on the left and right of :.

Presuming you're using .NET 3.5 and above, you could do this though:

foreach( string control in controls.Where(c => !c.Equals(string.Empty)) )
{
    foreach( int someStuff in moreStuff.Where(s => !s.Equals(0)) )
    {
    }
}
Dave
Nice feature, even though I still find this less readable ;)
x3ro
I am using 3.5 but can't see this feature.. weird.
ApoY2k
Are you including System.Linq? Where() is an extension method on IEnumerable.
Dave
+4  A: 

What about spliting the inner code into separate functions?

foreach (String control in controls)
{
 if (!control.Equals(String.Empty))
 {
   foo(control);
 }
}
merxbj
this is always a good answer ;) (+1)
atamanroman