优化“这种”循环

时间:2012-09-20 22:28:45

标签: c# optimization loops comparison boolean

我现在(并且过去曾经)使用这个循环来查看自定义类的数组,并确保数组中每个类的布尔成员值相等。是否有更好的(更有效,更简单的代码)方法来做到这一点?

由于这种解释非常糟糕,而且由于缺乏更好的解释方法,我只会问:“有没有更好的方法来优化'这个'循环?”

//set to true so the loop runs
boolean AllArentEqual = true;

while (AllArentEqual){
    //do some stuff to make stuff equal        



    ///// Check if stuff is equal /////
    //set to false to determine later
    AllArentEqual = false;

    //check if any aren't equal
    for (int i = 1; i < anArrayOfClass.length; i++){
        if (anArrayOfClass[i - 1].BooleanValue != anArrayOfClass[i].BooleanValue){
            //one isn't equal so set the loop to be re-run
            AllArentEqual = true;
        }
    } 


} //loop until stuff is equal

3 个答案:

答案 0 :(得分:2)

一个明显的小改进是增加了break

for (int i = 1; i < anArrayOfClass.length; i++){
    if (anArrayOfClass[i - 1].BooleanValue != anArrayOfClass[i].BooleanValue){
        //one isn't equal so set the loop to be re-run
        AllArentEqual = true;
        break;   // We're done in this round
    }
}

一旦确定并非所有人都是平等的,就没有必要进一步检查。

答案 1 :(得分:1)

我会通过提取一个方法来重做这一点,然后可能做类似的事情:

AttemptMakeEqual(anArrayOfClass);
while (anArrayOfClass.Any(c => c.BooleanValue != anArrayOfClass[0].BooleanValue))
{
    AttemptMakeEqual(anArrayOfClass);
}


// Extract out a method to:
void AttemptMakeEqual(YourClass[] values)
{
    //do some stuff to make stuff equal  
}

如果您有可能拥有“所有相等”的值,并且您并不总是需要先运行操作(即:您的新版本),您可以这样做:< / p>

while (anArrayOfClass.Any(c => c.BooleanValue != anArrayOfClass[0].BooleanValue))
{
    //do some stuff to make stuff equal  
}

答案 2 :(得分:0)

我可能会这样做:

class Widget
{
  public Widget( bool truthiness )
  {
    this.Truthiness = truthiness ;
  }
  public bool Truthiness { get ; private set ; }
}

class FooBar
{
  private Widget[] Widgets { get ; private set; }

  private Widget[] GetSomeWidgets()
  {
      throw new NotImplementedException() ;
  }
  public FooBar()
  {
    Widgets = GetSomeWidgets() ;
  }

  private void WorkOnWidgets()
  {
    throw new NotImplementedException() ;
  }

  public void MakeEqual()
  {
    bool areEqual ; // zero or one widget and it's not a problem
    while ( !(areEqual=CheckIfAllWidgetsEqual()) )
    {
      WorkOnWidgets() ;
    }
    return ;
  }

  public bool CheckIfAllWidgetsEqual()
  {
    bool value = true ;
    if ( Widgets.Length > 1 )
    {
      Widget first        = Widgets[0] ;
      Widget firstUnequal = Widgets.Skip(1).FirstOrDefault( x => x.Truthiness != first.Truthiness ) ;
      value = firstUnequal != null ;
    }
    return value ;
  }

}
相关问题