[Coding] How to check a lot of booleans at once

Discussion in 'Mixed Languages' started by Stannieman, Jan 8, 2011.

  1. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    I have 68 booleans and there are going to be more. I need check all of them if they are false.

    If all are false then
    do something
    else (if only 1 of them is true)
    do something
    end if

    Is there an easier way then
    If bln1 = false and bln2 = false and bln3 = false....?

    Thanks
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. BobSheep

    BobSheep MDL Guru

    Apr 19, 2010
    2,330
    1,377
    90
    #2 BobSheep, Jan 8, 2011
    Last edited by a moderator: Apr 20, 2017
    Here's an example in c# VS 2008

    Code:
    bool[] flags = new bool[68];
    
    for (int i = 0; i < flags.Length; i++)
        flags = false;
    
    flags[0] = true; // comment this line out and allfalse will be true, leave it in and allfalse will be false
    
    bool allfalse = !flags.Contains(true);
     
  3. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    #3 Stannieman, Jan 8, 2011
    Last edited by a moderator: Apr 20, 2017
    (OP)


    So I really need to make an array first?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  4. BobSheep

    BobSheep MDL Guru

    Apr 19, 2010
    2,330
    1,377
    90
    Yes, then you can use set operations, linq or lambda expressions.
     
  5. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    Ok thanks!
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  6. Calistoga

    Calistoga MDL Senior Member

    Jul 25, 2009
    421
    199
    10
    #6 Calistoga, Jan 16, 2011
    Last edited by a moderator: Apr 20, 2017
    In the spirit of reusability

    I'd like to add one more way to solve the problem :)

    You can define a method that accepts infinite Boolean arguments:
    Code:
    static bool IsAllFalse(params bool[] booleans)
    {
        foreach (bool boolean in booleans)
            if (boolean) return false;
    
         return true;
    }
    
    Usage:
    Code:
    // Returns true (all values are false)
    IsAllFalse(false, false, false, false, false, false);
    
    // Returns false (one or more values are true)
    IsAllFalse(false, false, false, false, false, false, true);
    
     
  7. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    #7 Stannieman, Jan 17, 2011
    Last edited by a moderator: Apr 20, 2017
    (OP)
    Thanks Calistoga
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...