er-v
er-v

Reputation: 4465

C# analog for sql in operator

There is in operator in SQL

SELECT * FROM MyTable WHERE id IN (1, 2, 3, 4, 5)

Is there similar sintax in C#, I mean

if(variable in (1, 2, 3, 4, 5)){
}

Upvotes: 7

Views: 1340

Answers (5)

pblasucci
pblasucci

Reputation: 1778

There isn't a good one but you can write it yourself as an extension method:

public static class Extensions
{
  public static bool In<T>(this T value, params T[] items)
  {
      return items.Contains(value);
  }
}

if (v.In(1,2,3,5)) { /* do stuff */ }

I haven't tested it, but it should be good.

UPDATE: As suggested by OP, I've corrected a few typos.

Upvotes: 10

LukeH
LukeH

Reputation: 269408

If you're using .NET 3.5 or newer then you can use Contains:

if (new[] { 1, 2, 3, 4, 5 }.Contains(variable))
{
     // do something
}

Upvotes: 2

ChaosPandion
ChaosPandion

Reputation: 78272

It is easy enough to put together an extension.

public static bool In<T>(this T value, params T[] items) where T : IEquatable<T>
{
    foreach (var item in items)
    {
        if (value.Equals(item))
        {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

With Enumerable.Contains

new int[]{1,2,3,4,5}.Contains(variable)

Upvotes: 1

Amitabh
Amitabh

Reputation: 61197

You can have

int[] data = {1, 2, 3, 4, 5};

if(data.Contains(variable))
{

}

Upvotes: 14

Related Questions