views:

136

answers:

8

I have this function:

    public bool IsValidProduct(int productTypeId)
    {
        bool isValid = false;

        if (productTypeId == 10 ||
            productTypeId == 11 ||
            productTypeId == 12)
        {
            isValid = true;
        }

        return isValid;
    }

but I'm wondering if there's an easier way to write it, such as:

    public bool IsValidProduct(int productTypeId)
    {
        bool isValid = false;

        if (productTypeId.In(10,11,12))
        {
            isValid = true;
        }

        return isValid;
    }

I know I could write an extension method to handle this, I'm just curious if there's already something out there or if there's a better way to write it.

+11  A: 
new [] {10, 11, 12}.Contains(productTypeId)
Mehrdad Afshari
A: 

You can use the Contains extension method from .NET 3.5. It works on all enumerable types:

if (new [] { 10, 11, 12 }.Contains(productTypeId))
{
    ...
}
Judah Himango
+1  A: 

I don't think there's anything in the framework so you'll have to write your own extension method. The closest you can get with linq is something like:


if(new[] { 10, 11, 12 }.Contains(productTypeId)) { ... }
Lee
+3  A: 

Hmm, you could do this:

public bool IsValidProduct(int productTypeId)
{
    bool isValid = false;

    if (new[] {10,11,12}.Contains(productTypeId))
    {
        isValid = true;
    }

    return isValid;
}

or if you want the same thing shorter:

public bool IsValidProduct(int productTypeId)
{
    return (new[] {10,11,12}.Contains(productTypeId));
}
Botz3000
+2  A: 

You could do something along the lines of:

new int[] { 10,11,12 }.Contains(productTypeID);

or go further an create an extension for int along the lines of:

public static bool In(this int i, params int[] ints)
{
    return ints.Contains(i);
}

With a usage of:

if (productTypeID.In(10,11,12)) { ... }

I wouldn't say they are the most efficient, but possible yes.

Quintin Robinson
+4  A: 

Nope I don't believe so but you could write an extension method like so which allows your code to work exactly as written.

public static bool In<T>(this T source, params T[] args) {
    return args.Contains(source);
}

The array overhead is a bit much though. You would probably want to add special cases for a smaller fixed number of parameters.

JaredPar
wish this was already in linq, but this helps make the code nice and succinct
Nick
A: 

var validIds = new[] { 10, 11, 12 };
validIds.Contains(productId);

JontyMC
A: 

This would work if the numbers you want are all in a range, not quite "IN" functionallity, but you may find it useful.

if (Enumerable.Range(10, 3).Contains(productTypeId))
Chris Persichetti