Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically switch between comparing Less Than, Greater Than, or Equal To?

Tags:

c#

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#?

like image 419
Neil N Avatar asked Nov 27 '22 01:11

Neil N


2 Answers

Two options:

  1. Use CompareTo and Sign:
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;
  1. Use a delegate:
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));
like image 192
Jon Skeet Avatar answered Dec 24 '22 14:12

Jon Skeet


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

like image 32
jrista Avatar answered Dec 24 '22 14:12

jrista