Tuesday, April 01, 2008

One thing that I like about SQL is the IN operator which checks if an argument is equal to any of the listed elements. C#/.NET doesn't offer this kind of operator which forces us to use code similar to the one below:

int i = 5;
if (i == 5 || i == 4 || i == 3)
{
    return;
}

Wouldn't it be better if we could just write like this:

if (i.In(5, 4, 3))
{
    return;
}

What we need is a simple Extension Method:

public static bool In<T>(this T source, params T[] values)
{
    return values.Any(v => v.Equals(source));
}

Few things to notice. First I'm using generic type parameter T to avoid boxing for Value Types. Second, it would probably be a wise thing to write few overrides like this:

public static bool In(this IComparable source, params IComparable[] values)
{
    return values.Any(v => v.CompareTo(source) == 0);
}

And another one for generic version. Finally it would be wise to provide an overload that accepts IEqualityComparer, like like LINQ extension methods do.

Whatever you do, you just have to love Extension Methods :-)

Tuesday, April 01, 2008 9:32:49 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |