Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a better way to compare multiple values against a property and return true;

Tags:

string

c#

compare

I am looking for a standard / best practice for scenarios where I need to check the same property of an object against a list of values returning true if any of the values match the property.

Currently the code resembles this (I didn't write it, I am looking to refactor it)...

if (object.property == "string1"
                    || object.property == "string2"
                    || object.property == "string3"
                        || object.property == "string4"
                        || object.property == "string5"
                                || object.property == "string6"
                                || object.property == "string7"
                                    || object.property == "string8"
                                     || object.property == "string9"
                                        || object.property == "string10"
                                        || object.property == "string11"
                                            || object.property == "string12"
                                            || object.property == "string13"
                                                || object.property == "string14"
                                                || object.property == "string15")
like image 233
TXRAckAck Avatar asked Jan 27 '12 23:01

TXRAckAck


3 Answers

IEnumerable<string> items = new List<string>{ "string1", "string2" };

bool match = items.Contains(object.property);
like image 161
Jakub Konecki Avatar answered Oct 16 '22 05:10

Jakub Konecki


Other answers suggest using a List<string>, but HashSet<string> is better suited for this task:

HashSet<string> set = new HashSet<string>() { "string1", "string2", ..., "string15" }; 

if (set.Contains(object.Property))
    //... do something ...

Or, as anatoliiG suggests, let the compiler handle it:

switch (object.property)
{
    case "string1":
    case "string2":
    //...
    case "string15":
       //... do something ...
       break;
}
like image 36
phoog Avatar answered Oct 16 '22 06:10

phoog


You can put the values in a List<string> and then do this:

List<string> values = new List<string>() {"string1", "string2"};

if(values.Contains(object.Property)) return true;
like image 42
TheBoyan Avatar answered Oct 16 '22 06:10

TheBoyan