Home > C#, Code > A more concise way to match values in C#

A more concise way to match values in C#

January 28th, 2009

From time to time, a developer will need to match a value in a series of values to accomplish conditional logic of some sort. Recently, while working with a project which had a status value, I needed a concise way match the value and do something useful.

Normally, I would write C# code that looks like this:

// Hard-coded for example
string status = "ww";

if (status == "ww" || status == "r" || status == "bw" ||
    status == "nb" || status == "qb" || status == "nt")
{
	// do something interesting
}
else if...
else if...
else...

However, after my hands tired out from typing (even with intellisense), I came up with the following:

// Hard-coded for example
string status = "ww";

if (new[] { "ww", "r", "bw", "nb", "qb", "nt" }.Contains(status))
{
    // do something interesting
}
else if...
else if...
else...

If the array of values contains an equal value to the status, then success. As you can see, the code is much easier to read and requires less typing. Enjoy!

[Update: Changed to use implicitly typed array (requires C# 3.0) instead of List<string>. Thanks manitra!]

rgillette C#, Code , ,

  1. adam
    May 1st, 2009 at 11:24 | #1

    List is a costly type to use. I would use a switch statement:

    string status = “ww”;

    switch (status)
    {
    case “ww”:
    case “r”:
    case “bw”:
    case “nb”:
    case “qb”:
    case “nt”:
    //do something here
    break;
    default:
    //else
    break;
    }

  2. May 1st, 2009 at 13:05 | #2

    Adam- I totally agree it doesn’t win an award for speed or resource consumption, but it is more concise and less verbose than a switch statement. For the particular project in which this was used, performance definitely wasn’t key and I just thought it was an interesting way to match values. However, performance is definitely a consideration with a site like, oh, ping.fm for example. ;)

    Thanks for the comment!

  3. July 23rd, 2009 at 06:27 | #3

    Hello,

    Nice tip :)

    Since C# 3, you can even remove a word and use array instead of list :
    if (new[] { “ww”, “j”, “d” }.Contains(status))
    {
    //do something interesting
    }

    Further more, the performance and memory usage will decrease … yeah :)

  4. July 23rd, 2009 at 07:26 | #4

    Thanks manitra! I knew about implicitly typed array declarations in C# 3.0, but it slipped my mind to use it. Thanks for the great feedback!

  1. No trackbacks yet.