如何从一组布尔值中返回一个布尔值?

时间:2014-01-29 00:30:36

标签: c# boolean return

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 个答案:

答案 0 :(得分:3)

使用以下linq查询:

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

另外,请考虑使用List<bool>代替ArrayList

如果您只想验证是否所有文件都存在,这是最简单的:

List<string> fileNames = new List<string>();    
return fileNames.All(File.Exists);

答案 1 :(得分:1)

我认为你没有正确设置returnType。在设置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
    }
}

答案 2 :(得分:0)

//you must add this below your foreach in MethodDetails()
foreach (var element in tempList)
    {
        if(element.Equals(false))
            return false;
    }

return true;

希望这会有所帮助:)