Basically I am giving the user an option to filter a set of files based on thier size.
The user picks a comparison type (Greater Than, Less Than, Equal To) from a drop down list, and then enters a size, in bytes, to compare to. This is what I have so far:
switch (cmboCompareType.SelectedText)
{
case "Greater Than":
fileOK = fi[i].Length > int.Parse(txtByteValue.Text);
break;
case "Less Than":
fileOK = fi[i].Length < int.Parse(txtByteValue.Text);
break;
case "Equal To":
fileOK = fi[i].Length == int.Parse(txtByteValue.Text);
break;
}
Is there a more elegant way to do this sort of comparison without repeating so much code in C#?
Two options:
int requiredSign;
switch (cmboCompareType.SelectedText)
{
case "Greater Than": requiredSign = 1; break;
case "Less Than": requiredSign = -1; break;
case "Equal To": requiredSign = 0; break;
default: throw new ArgumentException();
}
fileOK = Math.Sign(fi[i].Length.Compare(txtByteValue.Text)) == requiredSign;
static readonly Func<int, int, bool> GreaterThan = (x, y) => x > y;
static readonly Func<int, int, bool> LessThan = (x, y) => x < y;
static readonly Func<int, int, bool> Equal = (x, y) => x == y;
...
Func<int, int, bool> comparison;
switch (cmboCompareType.SelectedText)
{
case "Greater Than": comparison = GreaterThan; break;
case "Less Than": comparison = LessThan; break;
case "Equal To": comparison = Equal; break;
default: throw new ArgumentException();
}
fileOK = comparison(fi[i].Length, int.Parse(txtByteValue.Text));
int value = int.Parse(txtByteValue.Text);
int len = fi[i].Length;
switch (cmboCompareType.SelectedText)
{
case "Greater Than": fileOK = len > value; break;
case "Less Than": fileOK = len < value; break;
case "Equal To": fileOK = len == value; break;
}
TADA! Less repetition. ;P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With