Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement - 'or' but NOT 'and'

In C Sharp, how can I set up an if statement that checks if one of several conditions is true? It must be only one of the conditions, if zero or two or more are true the if should be false.

like image 783
Wilson Avatar asked May 24 '12 20:05

Wilson


2 Answers

You could write a helper method. This has the advantage that it short circuits, only evaluating exactly as many as necessary,

public static bool IsExactlyOneTrue(IEnumerable<Func<bool>> conditions) {
    bool any = false;
    foreach (var condition in conditions) {
        bool result = condition();
        if (any && result) {
            return false;
        }
        any = any | result;
    }
    return any;
}
like image 93
jason Avatar answered Nov 07 '22 14:11

jason


List<Func<Customer, bool>> criteria = new List<Func<Customer, bool>>();

criteria.Add(c => c.Name.StartsWith("B"));
criteria.Add(c => c.Job == Jobs.Plumber);
criteria.Add(c => c.IsExcellent);

Customer myCustomer = GetCustomer();

int criteriaCount = criteria
  .Where(q => q(myCustomer))
  // .Take(2)  // optimization
  .Count()
if (criteriaCount == 1)
{
}

Linq implementation of Jason's method signature:

public static bool IsExactlyOneTrue(IEnumerable<Func<bool>> conditions)
{
  int passingConditions = conditions
    .Where(x => x())
    // .Take(2) //optimization
    .Count();
  return passingConditions == 1;
}
like image 33
Amy B Avatar answered Nov 07 '22 14:11

Amy B