我正在寻找一种标准/最佳实践,我需要检查对象的相同属性,如果任何值与属性匹配,则返回值为true的值。
目前代码类似于此(我没有写它,我希望重构它)...
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")
答案 0 :(得分:9)
IEnumerable<string> items = new List<string>{ "string1", "string2" };
bool match = items.Contains(object.property);
答案 1 :(得分:4)
其他答案建议使用List<string>
,但HashSet<string>
更适合此任务:
HashSet<string> set = new HashSet<string>() { "string1", "string2", ..., "string15" };
if (set.Contains(object.Property))
//... do something ...
或者,正如anatol的建议,让编译器处理它:
switch (object.property)
{
case "string1":
case "string2":
//...
case "string15":
//... do something ...
break;
}
答案 2 :(得分:1)
您可以将值放在List<string>
中,然后执行以下操作:
List<string> values = new List<string>() {"string1", "string2"};
if(values.Contains(object.Property)) return true;
答案 3 :(得分:0)
您可以尝试LINQ以获得更简洁的代码,例如:
bool match = new string[] { "string1", "string2" }.Any(p => p == object.property);