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")
IEnumerable<string> items = new List<string>{ "string1", "string2" };
bool match = items.Contains(object.property);
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;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With