Friday 19 August 2011

Implementing the SQL "In" keyword behavior in C#

Often when checking whether a value matches a value in a list of values, we use syntax like this:

if (myObject.MyProperty.Equals("value1") || myObject.MyProperty.Equals("value2") || myObject.MyObject.Equals("value3"))
{
// do something
}

This syntax may become cumbersome especially if you need to check your object's value against more than 2 or 3 values. For this problem, one may ask if the SQL "IN" keyword like behavior is available in the .Net Framework. Unfortunately, the anwser is NO. You have to implement this by yourself.

The method below provides functionality equivalent to the SQL "IN" keyword, i.e., it checks if a value is found in a list of values.



Code Snippet



  1. public static bool ValueIn<T>(T testValue, params T[] values)

  2.         {

  3.             return ((IList<T>)values).Contains(testValue);

  4.         }






Then our code sysntax will look something like this:

if (MyStaticClass.ValueIn(myObject.MyProperty, "value1", "value2", "value3")
{
// do something
}

As you may have noticed, the code syntax becomes much more readable and less cumbersome to write.

By using extension methods in .Net, the code syntax could be further simplified. For example, we could write:

if (myObject.MyProperty.ValueIn("value1", "value2", "value3")
{
// do something
}

Note:



  1. In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces.

    These implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

No comments: