Ternary operator in foreach

I am currently struggling with about 5 nested if statements, and it is becoming quite confusing to look at all of them.

So, I was thinking of 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
    }
   }
 }

Here's what it looks like now. Thats my idea on how to make it look a little nicer:

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. Poor programming to solve it this way and 2. Will it work the way I want?

+3
source share
4 answers

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 is more readable :)

+3
source

No, it will not, the ternary operator must have values ​​to the left and to the right of :.

, .NET 3.5 , , :

foreach( string control in controls.Where(c => !c.Equals(string.Empty)) )
{
    foreach( int someStuff in moreStuff.Where(s => !s.Equals(0)) )
    {
    }
}
+12

?

foreach (String control in controls)
{
 if (!control.Equals(String.Empty))
 {
   foo(control);
 }
}
+5

, . , - , . , ( ).

, LINQ , , , .

EDIT: :

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
}
+2

Source: https://habr.com/ru/post/1762604/


All Articles