Pascal
Pascal

Reputation: 2974

C# equivalent for Delphi's in

What is the equivalent in C# for Delphi's in syntax, like:


  if (iIntVar in [2,96]) then 
  begin
    //some code
  end;

Thanks

Upvotes: 11

Views: 4821

Answers (7)

Mauricio Naozuka
Mauricio Naozuka

Reputation: 36

I know this is an old topic, but I like this because it's cleaner. (Tested in .NET 6)

public static class FooUtils
{
    public static bool In(this object obj, params object[] arr)
    {
        return arr.Contains(obj);
    }
}

Usage:

int myNumber = 5;
if (myNumber.In(1, 5, 10))
{
    // do something                
}

Upvotes: 1

TrueWill
TrueWill

Reputation: 25523

To expand upon what Mason Wheeler wrote in a comment, this would be HashSet<T>.Contains (under .NET 3.5).

int i = 96;
var set = new HashSet<int> { 2, 96 };

if (set.Contains(i))
{
   Console.WriteLine("Found!");
}

Upvotes: 3

Gabe
Gabe

Reputation: 86718

I prefer a method like defined here: Comparing a variable to multiple values

Here's the conversion of Chad's post:

public static bool In(this T obj, params T[] arr)
{
    return arr.Contains(obj);
}

And usage would be

if (intVar.In(12, 42, 46, 74) ) 
{ 
    //TODO: Something 
} 

or

if (42.In(x, y, z))
    // do something

Upvotes: 9

CaffGeek
CaffGeek

Reputation: 22054

In .Net, .Contains is the closest, but the syntax is the opposite of what you wrote.

You could write an extension method to be able to create a .In method

public static bool In<T>(this T obj, IEnumerable<T> arr)
 {
  return arr.Contains(obj);
 }

And usage would be

if (42.In(new[] { 12, 42, 46, 74 }) )
{
    //TODO: Something
}

Upvotes: 5

Johnno Nolan
Johnno Nolan

Reputation: 29659

You could write an extension method

 public static bool In(this int value, int[] range)
    {
        return (value >= range[0] && value <= range[1]);
    }

Upvotes: 2

plinth
plinth

Reputation: 49189

You can create this extension method:

public static class ExtensionMethods
{
    public static bool InRange(this int val, int lower, int upper)
    {
        return val >= lower && val <= upper;
    }
}

then you can do this:

int i = 56;
if (i.InRange(2, 96)) { /* ... */ }

Upvotes: 3

Randolpho
Randolpho

Reputation: 56391

There is no such equivalent. The closest is the Contains() extension method of a collection.

Example:

var vals = new int[] {2, 96};
if(vals.Contains(iIntVar))
{
  // some code
}

Upvotes: 5

Related Questions