5

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

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

Thanks!

FrankVDB
  • 235
  • 2
  • 4
  • 16
  • 1
    You could create a collection of string literals and check if that collection contains `interSubDir`. – David Apr 05 '17 at 12:47
  • 1
    You're going to have to do the comparison for each target at some point, whether it's in loop or individually. Are you just trying to make it more readable? – Matthew Watson Apr 05 '17 at 12:50
  • Typically, when you're checking if X equals A, B, C, D, etc, you have to check each one. There is no real shortcut. Sometimes, you can group like things into an array and perform your check using `Any`, but if what you do depends on what you are checking against that won't help you. –  Apr 05 '17 at 12:52

3 Answers3

10

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.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
6

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);
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
1

Linq could be of use. listToCheckAgainst could be a simple variable or a private/public property.

var listToCheckAgainst = new[] { "de", "DE-de" };

if(listToCheckAgainst.Any(x => interSubDir.Equals(x)));
iownbey
  • 69
  • 5
Mantas Čekanauskas
  • 2,218
  • 6
  • 23
  • 43