C # analog for sql in statement

SQL statement exists

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

Is there any similar syntax in C #, I mean

 if(variable in (1, 2, 3, 4, 5)){ } 
+7
c #
source share
5 answers

Not good, but you can write it 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 have not tested it, but it should be fine.

UPDATE: as suggested by OP, I fixed a few typos.

+10
source share

You may have

 int[] data = {1, 2, 3, 4, 5}; if(data.Contains(variable)) { } 
+14
source share

If you are using .NET 3.5 or later, you can use Contains :

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

With Enumerable.Contains

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

Easy to assemble 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; } 
+1
source share

All Articles