The Code Page
A series of development tips and code examples by Gabriel McAdams
Nov 14

There are several posts on the various forum and question/answer sites where people are wondering if there is an 'In' method in C#.  That, or if there is another quick way to determine if a variable value is one of the values in a given list.

There are a few ways to do this now.  Many of them are tedious.  Adding extra lines of code to do something that should be very simple.

You could use a switch case:

bool found;
string myStr = "str3";
 
switch (myStr)
{
    case "str1":
    case "str2":
    case "str3":
    case "str4":
        found = true;
        break;
    default:
        found = false;
        break;
}

Or you can use the logical OR operator:

string myStr = "str3";
bool found = (myStr == "str1" || myStr == "str2" || myStr == "str3" || myStr == "str4");

Or my favorite (until now) – Use a generic list with an initializer:

string myStr = "str3";
bool found = new List<string>() {
    "str1",
    "str2",
    "str3",
    "str4"
}.Contains(myStr);

Now, with this very small extension method, that all goes away, and is replaced with a single line of code.

using System.Linq;

public static class ExtensionMethods
{
    public static bool IsIn<T>(this T source, params T[] values)
        if (values == null) { return false; }
        return values.Contains(source);
    }
}

You can use it to do something like this:

string myStr = "str3";
bool found = myStr.IsIn("str1", "str2", "str3", "str4");

By using a generic extension method, it allows you to do this with any object type (as long as a good Equals is defined).  It works with int:

int myNum = 2;
bool found = myNum.IsIn(1, 2, 3, 4);

or you could use it with DateTime:

DateTime myDate = DateTime.Today;
bool found = myDate.IsIn(
    DateTime.Now,
    DateTime.Today,
    DateTime.Parse("11/1/2005")
);

I hope you find this useful.  Feel free to contact me with any questions.

Tags:

Comments

Add comment








biuquote
  • Comment
  • Preview


Loading



.