This morning I was working on some legacy code (code I find that has no corresponding unit tests assigned to it) and found myself wanting the C# equivalent of the SQL “NOT IN” and “IN” statements. For example,
SELECT COUNT(*) FROM
WHERE
So, I wrote a simple little extension method class to do just that:
static public class Extensions
{
static public bool IsIn(this Int32 value_, params Int32[] list_)
{
// LINQ is less efficient...
// return list_.Where(v => { return v == value_;}).Count() > 0;
// ...than this:
foreach (var value in list_)
if (value == value_)
return true;
return false;
}
static public bool NotIn(this Int32 value_, params Int32[] list_)
{
return !IsIn(value_, list_);
}
}
Now you can write code like this:
public void Example1 (Int32 [] someList_)
{
if (5.IsIn(someList_)
DoSomethingSexy();
}
… or like this:
public void Example2 (Int32 value_)
{
if (value_.NotIn(_myList))
DoSomethingElseSexy();
}
Enjoy!











October 14th, 2009 1:59 pm
Nice. You have to love extension methods. Depending on how you’re using this method, you might want to consider making it generic. Then you’re not limiting yourself to Int32. Food for thought. Great post!