Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Compare one string variables to multiple other string (String.Equals) [duplicate]

Tags:

string

c#

equals

Do you have an idea to avoid doing multiple String.Equals? For instance:

if (interSubDir.Equals("de") || interSubDir.Equals("de-DE"))

Thanks!

like image 563
FrankVDB Avatar asked Dec 05 '22 15:12

FrankVDB


1 Answers

If you are simply trying to make it more readable, or require less typing, you can write a string extension method like so:

public static class StringExt
{
    public static bool EqualsAnyOf(this string value, params string[] targets)
    {
        return targets.Any(target => target.Equals(value));
    }
}

Which you can use as follows:

if (interSubDir.EqualsAnyOf("de", "de-DE"))

Or

if (interSubDir.EqualsAnyOf("de", "de-DE", "en", "en-GB", "en-US"))

and so on.

like image 177
Matthew Watson Avatar answered Mar 15 '23 22:03

Matthew Watson