Search code examples
c#stringequals

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


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

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

Thanks!


Solution

  • Create collection of values:

    string[] values = { "de", "de-DE" };
    

    Use Contains method:

    if (values.Contains(interSubDir))
    

    It gives O(n) performance.

    If your collection is very big, then you can use Array.BinarySearch method, that gives you O(log n) performance.

    if (Array.BinarySearch(values, interSubDir) >= 0)
    

    However, the collection must be sorted first.

    Array.Sort(values);