简体   繁体   中英

What is a smart way to check if a string variable value is one of a specified set of value in C#?

I am writing a simple C#.NET application where I have an if condition where I am checking if a string variable value is a string or another string or another string or another one, etcetc.

Something like this:

if(protocollo == "2019/0002391" || protocollo == "2019/0002390" || protocollo == "2019/0001990" || ........)

This solution works but it is not so elegant. What could be a smarter way to implement the same behavior?

I agree with @JeroenMostert that it really depends on the context of the rest of your application. That said, using an array of strings and checking if your string is in there is a nice straightforward solution. There are certianily solutions that would scale better, take a look at HashSet .

string[] s = new string[] { "2019/0002391", "2019/0002390", "2019/0001990", ... };

if (s.Contains(protocollo)) {
    // fill in here
}

You never said, so I'm making the assumption that the strings you're checking against is hard-coded and not something that changes often. To that end, you could create a string[] or HashSet<string> in a static class so it only initializes the one time, then expose a method for checking a second string against the valid ones.

void Main()
{
    Console.WriteLine(Protocols.ValidProtocol("2019/0002391")); //True
    Console.WriteLine(Protocols.ValidProtocol("2018/0000000")); //False
}

// Define other methods and classes here
public static class Protocols
{
    public static bool ValidProtocol(string protocol)
    {
        return _validProtocols.Contains(protocol);
    }

    private static readonly HashSet<string> _validProtocols = new HashSet<string>
    {
        "2019/0002391",
        "2019/0002390",
        "2019/0001990"
        //etc, etc...
    };
}

A solution like this would probably not be ideal if the list of string s you need to check against changes often. You'd probably want to pull the list from an external source like a file or a database if you need to modify it often.

I had some code similar to your example in a static extension method. I didn't want to have to instantiate an array every time the method was called, but I wanted to improve the readability of the code.

I improved the code using the switch expression which was added in C# 8. Here is the what your example might look like if implemented with a switch expression. Depending on what your code does if the condition is true you may be able to improve on this, but this is the basics.

var isProtocolloMatch = protocollo switch
{
    "2019/0002391" => true,
    "2019/0002390" => true,
    "2019/0001990" => true,
    _ => false
};

if (isProtocolloMatch)
{
    // do stuff
}

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