foreach中的三元运算符

F.P*_*F.P 3 c#

我目前正在努力解决大约5个嵌套的if语句,并且看起来很困难.

因此,我考虑添加三元运算符而不是ifs进行简单检查,请参阅

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
    }
   }
 }
Run Code Online (Sandbox Code Playgroud)

那就是现在的样子.多数民众赞成我的想法,如何使它看起来更好一点:

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
 }
}
Run Code Online (Sandbox Code Playgroud)

所以,问题是:1.这是不好的编程,这样解决它2.它会按照我想要的方式工作吗?

Dav*_*wns 12

不,它不会,三元运算符必须在左侧和右侧具有值:.

假设您使用的是.NET 3.5及更高版本,您可以这样做:

foreach( string control in controls.Where(c => !c.Equals(string.Empty)) )
{
    foreach( int someStuff in moreStuff.Where(s => !s.Equals(0)) )
    {
    }
}
Run Code Online (Sandbox Code Playgroud)


mer*_*xbj 5

将内部代码拆分成单独的函数怎么样?

foreach (String control in controls)
{
 if (!control.Equals(String.Empty))
 {
   foo(control);
 }
}
Run Code Online (Sandbox Code Playgroud)