Alaa Jabre
Alaa Jabre

Reputation: 1893

Shortcut to use boolean operators on multiple values

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?

Upvotes: 2

Views: 1138

Answers (6)

Tim Schmelter
Tim Schmelter

Reputation: 460158

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)

Upvotes: 8

Joe White
Joe White

Reputation: 97748

Honestly, the first thing that comes to my mind is the good old Introduce Explaining Variable refactoring, which not only reduces the duplication but also makes your code more self-explanatory:

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

Upvotes: 1

Oded
Oded

Reputation: 499092

var listToCheck = new int[]{1,2,3};
var innerValue = variable1.innerValue.level2.innerValue;

bool result = listToCheck.Contains(innerValue);

Upvotes: 1

George Duckett
George Duckett

Reputation: 32438

using System.Linq;
...
bool result = new[] {1, 2, 3}.Contains(variable1.innerValue.level2.innerValue);

Upvotes: 1

akton
akton

Reputation: 14386

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

Upvotes: 1

Justin Harvey
Justin Harvey

Reputation: 14672

How about

(new List<int>(){1,2,3}).Exists(i=>i == variable1.innerValue.level2.innerValue)

Upvotes: 0

Related Questions