2014-01-29 157 views
0

aList中的每个项目都返回true或false。我试图根据以下要求返回一个布尔值:如何从一组布尔值返回单个布尔值?

如果aList中的所有项都返回true,我想MethodDetails()也返回true以及。

但是,如果aList中的任何元素返回false,我希望这些元素中的每一个都保持其返回值,但MethodDetails()返回false。

public class aClass 
{ 
    bool returnType; 
    private list aList; 
    ArrayList tempList = new ArrayList(); 

    protected override object MethodDetails() 
    { 
     foreach (var element in aList) 
     { 
      MainMethod(); 
      tempList.Add(returnType); 
     } 

     //this is what I tried but it didn't work 
     /*if (tempList.Contains(returnType)) 
     { 
      return false; 
     } 
     else 
     { 
      return returnType; 
     }*/ 
    } 

    private bool MainMethod() 
    { 
     if (File.Exists(aFile) 
     { 
      if (int x != int y) 
      { 
       return false; 
       returnType = false; 
      } 
      else 
      { 
       return true; 
       returnType = true; 
      } 
     } 
     else 
     { 
      return false 
      returnType = false; 
     } 
    } 
} 

回答

3

使用以下LINQ查询:

return !tempList.OfType<bool>().Any(x => !x); 

而且,考虑使用的List<bool>代替ArrayList

如果你只是想验证是否存在这所有的文件是简单的:

List<string> fileNames = new List<string>();  
return fileNames.All(File.Exists); 
0
//you must add this below your foreach in MethodDetails() 
foreach (var element in tempList) 
    { 
     if(element.Equals(false)) 
      return false; 
    } 

return true; 

希望这有助于:)

1

我不认为你是正确设置返回类型。您在设置returnType值之前从MainMethod返回。我认为你的MainMethod应该看起来像这样

private bool MainMethod() 
{ 
    if (File.Exists(aFile) 
    { 
     if (int x != int y) 
     { 
      returnType = false; // Changed 
      return false; 

     } 
     else 
     { 
      returnType = true; // Changed 
      return true; 
     } 
    } 
    else 
    { 
     returnType = false; // Changed 
     return false 
    } 
}