[英]Need a better way to compare multiple values against a property and return true;
我正在尋找一個標准/最佳實踐的場景,我需要檢查一個對象的相同屬性對一個值列表返回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")
IEnumerable<string> items = new List<string>{ "string1", "string2" };
bool match = items.Contains(object.property);
其他答案建議使用List<string>
,但HashSet<string>
更適合此任務:
HashSet<string> set = new HashSet<string>() { "string1", "string2", ..., "string15" };
if (set.Contains(object.Property))
//... do something ...
或者,正如anatoliiG建議的那樣,讓編譯器處理它:
switch (object.property)
{
case "string1":
case "string2":
//...
case "string15":
//... do something ...
break;
}
您可以將值放在List<string>
,然后執行以下操作:
List<string> values = new List<string>() {"string1", "string2"};
if(values.Contains(object.Property)) return true;
您可以嘗試LINQ以獲得更簡潔的代碼,例如:
bool match = new string[] { "string1", "string2" }.Any(p => p == object.property);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.