Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut to use boolean operators on multiple values

Tags:

c#

First off, sorry if the title isn't clear or descriptive; I didn't know what to write exactly.

I'm wondering if there is a better way to do this operation:

bool result = variable1.innerValue.level2.innerValue == 1 || 
              variable1.innerValue.level2.innerValue == 2 || 
              variable1.innerValue.level2.innerValue == 3;

We can't write something like:

bool result = variable1.innerValue.level2.innerValue == (1 || 2 || 3);

This will give a syntax error.

Any ideas?

like image 947
Alaa Jabre Avatar asked Dec 18 '25 09:12

Alaa Jabre


2 Answers

You could use a collection as placeholder and Enumerable.Contains:

if(new[]{1, 2, 3}.Contains(variable1.innerValue.level2.innerValue))
{

}

or, for what it's worth, this extension:

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

which enables you to write this:

if(variable1.innerValue.level2.innerValue.In(1, 2, 3))
{

}

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

like image 156
Tim Schmelter Avatar answered Dec 20 '25 23:12

Tim Schmelter


In this case. you can do Enumerable.Range(1, 3).Contains(variable1.innerValue.level2.innerValue).

like image 36
akton Avatar answered Dec 20 '25 22:12

akton