Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to shorten the condition if it always compares to the same thing?

Tags:

c#

I have always found it annoying when I need to write a condition that compares the same item over and over again since I would have the type the item so many times:

string x = textBox1.Text;

if (x == "apple" || x == "orange" || x == "banana" ...)
...

I want something like this (but of course this is not correct syntax):

if (x == "apple" || "orange" || "banana" ...)

Is there a solution other than using an array of the strings?

like image 725
Kevin Cho Avatar asked Dec 03 '22 02:12

Kevin Cho


2 Answers

Your condition says: I'm true if I match any of the predefined values. In other words if I'm an element of a predefined set which is semantically the Contains method:

if (new [] { "apple", "orange", "banana" }.Contains(x))
{

}

Using an array provides much more flexibility in the future. You can extract it out, reuse it, store it, chache it etc. I always use "arrays and loops" when I have to deal with more than 2 known values.

Note: As Scott Chamberlain pointed out in the comments with using HashSet<T>.Contains greatly improves the performace:

var values = new HashSet<string> { "apple", "banana", "orange" };
if (values.Contains(x))
{

}
like image 158
nemesv Avatar answered Apr 28 '23 13:04

nemesv


What about an extension method?

public static class Extensions
{
   public static bool IsOneOf<T>(this T input, params T[] possibilites)
   {
      bool result = possibilites.Contains(input);
      return result;
   }
}

You could then rewrite your code to look like this:

string input = textBox1.Text;
if(input.IsOneOf("apple", "orange", "banana"))
{
    // ....
}
like image 34
Nikola Anusev Avatar answered Apr 28 '23 14:04

Nikola Anusev