TXRAckAck
TXRAckAck

Reputation: 51

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

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")

Upvotes: 5

Views: 7155

Answers (4)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

You can try LINQ for a more concise code, such as:

bool match = new string[] { "string1", "string2" }.Any(p => p == object.property);

Upvotes: 0

phoog
phoog

Reputation: 43046

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;
}

Upvotes: 4

TehBoyan
TehBoyan

Reputation: 6890

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;

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

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

bool match = items.Contains(object.property);

Upvotes: 9

Related Questions