C# extension method similar to Sql’s IN operator

Consider the code snippet below

if(a == x || a == y || a == z)

We can re-write this expression as:

  • Using array’s contains

 if( new [] {x,y,z}.Contains(a))

  • Using a similar syntax for the SQL’s IN operator by using extension

public bool IsIn(this T obj, params T[] collection) {
   return collection.Contains(obj);
}
And invoke as
if(a.IsIn(b, c, d)) { … }

Read more at Stackoverflow

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.