简体   繁体   中英

Is there a better way to code an if statement looking for a variable to match one of many?

I need to check that a variable has one of a few different values. Currently I have code lik this:

if (cName == "Products" || cName == "Packages" || cName == "Contents" || cName == "Packages") 
..
if (cName == "Products" || cName == "Packages" || cName == "Contents") 
..
etc

It doesn't look very clean to me. Is there some simpler one line way I could do this check? Some code where I would not have to keep repeating cName?

Yes.

switch (cName) 
{
    case "Products":
    case "Packages":
    case "Contents": // If cName is one of the above, execute code below
        ... // DO STUFF
        break;
    case "Some-other-value": // if cName is exactly Some-other-value, execute code below
        .. // DO STUFF
        break;
}

The C# way is considered to be the lambda way :

if( System.Array.Find( new string[]{ "Products", "Packages", "Contents" }, (s) => s == cName ) != null )
..

Or, alternatively:

using System.Linq;
..
if( new string[]{ "Products", "Packages", "Contents" }.Any( s => s == cName ) )
..

ICollection.Contains (or Enumerable.Any ) may be worth investigating...

var standardCategories = new [] { "Products", "Packages", "Contents" };
if (standardCategories.Contains(cName) || cName == "Fred") {
    ...
} else if (standardCategories.Contains(cName)) {
    ...
}

Do be aware that this does introduce "additional overhead", fsvo -- most of the time it Just Doesn't Matter, but be able to defend your decision :) As for me, I take tidier code any day and have never run into an issue with this approach, but I am also not a game developer.

(In this a particular case I'd use a nested if statement as the predicates seem amendable to such; the code above is just an example of usage. Note my use of "Fred" as "Packages" was being checked for ... twice.)

Happy coding.

You could also have a look at Extension Methods.

public static class StringExtensions
{
    public static bool EqualsAny(this string s, params string[] args)
    {
        return args.Contains(s);
    }

}

Then you could use this ike:

string cName = "Products";

if (cName.EqualsAny("Products", "Packages", "Contents", "Packages"))
{
}

try

List<string> myMatchList = new List<string> { "Products", "Packages", "Contents" };
if ( myMatchList.Contains ( cName ) )

OR the "inline-version" (BEWARE it not memory-/CPU-efficient)

if ( (new List<string> { "Products", "Packages", "Contents" }).Contains ( cName ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM