2

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?

Bjørn Madsen
  • 378
  • 2
  • 17
Alaa Jabre
  • 1,843
  • 5
  • 26
  • 52

6 Answers6

8

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)

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    As long as there are only a few values, an array is better. But if the list of values becomes big enough, consider switching to `HashSet.Contains`. – CodesInChaos Sep 11 '12 at 12:30
1

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

akton
  • 14,148
  • 3
  • 43
  • 47
1
using System.Linq;
...
bool result = new[] {1, 2, 3}.Contains(variable1.innerValue.level2.innerValue);
George Duckett
  • 31,770
  • 9
  • 95
  • 162
1
var listToCheck = new int[]{1,2,3};
var innerValue = variable1.innerValue.level2.innerValue;

bool result = listToCheck.Contains(innerValue);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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;
Joe White
  • 94,807
  • 60
  • 220
  • 330
0

How about

(new List<int>(){1,2,3}).Exists(i=>i == variable1.innerValue.level2.innerValue)
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30