3

i would like to ask if there a method making this condition shorter like in MSSQL because i have similar coditions also like this.

if(docType == "PO" || docType == "II" || docType == "IA" || docType == "IT"  || docType == "OV" || docType == "ID")
{

}

in MSSQL

SELECT * FROM Documents WHERE docType IN ("PO","II","IA","IT","OV") 
ayanix
  • 429
  • 1
  • 4
  • 9

6 Answers6

3

You could construct an array in C#, too:

if (new [] {"PO", "II", "IA", "IT", "IV"}.Contains(docType)) {
}

You could also use regex:

if (Regex.IsMatch(docType, "PO|II|IA|IT|IV")) {
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

One way to do this is to create a method with the params keyword that handles it for you. This allows you to pass any number of parameters and also the value you are checking

private bool IfContains(string needle, params string[] haystack)
{
    bool match = false;

    foreach(string val in haystack)
    {
        if(val == needle)
        {
            match = true;
            break;
        }
    }
    return match;
}

This can be called with an number of parameters like

if(IfContains("Hello", "Hi", "yo", "Hello"))
{
    //DoStuff
}
Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
1

Well:

var ids = new[] { "PO", "II", "IA", "IT", "OV", "ID" }
if (ids.Contains(docType)
{

}

You could even make it non case sensitive:

var ids = new[] { "PO", "II", "IA", "IT", "OV", "ID" }
if (ids.Contains(docType, StringComparer.InvariantCultureIgnoreCase)
{

}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Yes, put them in an array and simply do a contains

new[] {"a", "b", "c", "d"}.Contains(value)

instead of

if (value == "a" || value == "b" ...)

Ruskin
  • 1,504
  • 13
  • 25
1

You can check from list which you can use to find any doctype in the list :

var list = new List<string>(){"PO","II","IA","IT","OV"};
if(list.Any(x=>x == docType))
{

}
Akash KC
  • 16,057
  • 6
  • 39
  • 59
0

All the other answers are valid and nice, I'm just trying to be original here. I often use the following technique in my code to improve readability and use "real words".

I usually spend "more time" on the naming, could be DocTypeIsValid, but I really like having my bool functions starting with "has" or "is". The point here is just to improve reusability and readability.

private bool IsDoctypeValid(string docType){
       return docType == "PO" || docType == "II" || docType == "IT" || docType == "IV";
}

Note that you could use the technique found in other answers (the .Contains() for example) and put it inside the return method, it works the same :) The idea i'm trying to point out is to extract your if in a method, so you can do this later on, everywhere :

if (IsDoctypeValid(docType)){

}

which is super small and super readable.

Gil Sand
  • 5,802
  • 5
  • 36
  • 78