Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator in foreach

Tags:

c#

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?

like image 522
F.P Avatar asked Nov 22 '25 09:11

F.P


2 Answers

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)) )
    {
    }
}
like image 60
Dave D Avatar answered Nov 24 '25 21:11

Dave D


What about spliting the inner code into separate functions?

foreach (String control in controls)
{
 if (!control.Equals(String.Empty))
 {
   foo(control);
 }
}
like image 34
merxbj Avatar answered Nov 24 '25 21:11

merxbj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!