Thursday, March 11, 2010

Multi boolean compare

I run in to a problem where I had multiple boolean values each corresponding to a string value.
When one of the boolean values was true the corresponding string value would be used to populate a field in a report, but if more than one boolean value was true or all boolean value was false, empty string would be used to populate the report field.

This was solved by a lot of if´s, something like this:

if (boolean1 && !boolean2 && ...)
{
 SetField("value1");
}
else if (!boolean1 && boolean2 && ...)
{
 SetField("value2");
}
...
else
{
 SetField("");
}

When there was a lot of boolean/string value pairs there was a massive amount of if´s.
It made it kind of hard to read when most reports had about 150 fields.
That made me think, there has to be something I can do about it...
There might be a solution with linq involved but, I had to deal with .net 2.0 so no linq.

This is the solution I came up with:

public class MultiBooleanComparer
{
 private readonly List<bool> _keys;
 private readonly List<string> _values;

 public MultiBooleanComparer()
 {
  _keys = new List<bool>();
  _values = new List<string>();
 }

 public void Add(bool key, string value)
 {
  _keys.Add(key);
  _values.Add(value);
 }

 public string GetValue()
 {
  return ToString();
 }

 public override string ToString()
 {
  return _keys.FindAll(WhereTrue).Count != 1 ? string.Empty : _values[_keys.IndexOf(true)];
 }

 private static bool WhereTrue(bool obj)
 {
  return obj;
 }
}

MultiBooleanCompare multi = new MultiBooleanCompare();
multi.Add(boolean1, "value1");
multi.Add(boolean2, "value2");
multi.Add(boolean3, "value3");
multi.Add(boolean4, "value4");
multi.Add(boolean5, "value5");
SetField(multi.ToString());

No comments:

Post a Comment