Search code examples
c#booleanboolean-logicboolean-expression

Conditional bool check from tuple groups C#


I thought it was a simple problem, turned out no so simple at least for me.

I have

(bool isEqual, bool duplicateCheckEnabled) group1 = (false, false);
(bool isEqual, bool duplicateCheckEnabled) group2 = (true, true);
(bool isEqual, bool duplicateCheckEnabled) group3 = (true, true);
(bool isEqual, bool duplicateCheckEnabled) group4 = (false, true);
(bool isEqual, bool duplicateCheckEnabled) group5 = (false, false);

The values are populated from an external logic. I would each of those tuple property using another object. For all the groups from group1 to group5 that have duplicateCheckEnabled as true, I want to check if all the corresponding isEqual flags are true. For the given above values, I would only want group2, group3 and group4 isEqual to be considered (as per duplicateCheckEnabled flag true), so that the expression evaluates as

bool isDuplicate = group2.isEqual && group3.isEqual && group4.isEqual

Should I use an array to store only the groups that I want the isEqual comparison to apply?


Solution

  • Although this can be done without an array:

    bool isDuplicate = (!group1.duplicateCheckEnabled || group1.isEqual) &&
                       (!group2.duplicateCheckEnabled || group2.isEqual) &&
                       (!group3.duplicateCheckEnabled || group3.isEqual) &&
                       (!group4.duplicateCheckEnabled || group4.isEqual) &&
                       (!group5.duplicateCheckEnabled || group5.isEqual);
    

    You should still put all those values into an array/list, ideally of a custom struct/class.

    YourCustomStruct[] groups = { ... };
    bool isDuplicate = groups.Aggregate(true, (x, y) => x && (!y.DuplicateCheckEnabled || y.IsEqual));