2017-08-03 39 views
1

情況我有以下if條件:建築如果從陣列

if (!string.IsNullOrEmpty(str) && 
    (!str.ToLower().Contains("getmedia") && !str.ToLower().Contains("cmsscripts") && 
    !str.ToLower().Contains("cmspages") && !str.ToLower().Contains("asmx") && 
    !str.ToLower().Contains("cmsadmincontrols")) 
) 

我想創建關鍵字,而不是把多個AND條件的數組,你可以請幫助?

string[] excludeUrlKeyword = ConfigurationManager.AppSettings["ExcludeUrlKeyword"].Split(','); 

for (int i = 0; i < excludeUrlKeyword.Length; i++) 
{ 
    var sExcludeUrlKeyword = excludeUrlKeyword[i]; 
} 

如何從數組中構建相同的條件?

+0

使用LINQ的任何或我們可以在沒有LINQ的情況下編寫所有 – Oasis

+0

嗎? – SmartestVEGA

回答

1

的LINQ Any應該這樣做

if (!string.IsNullOrEmpty(str) && !excludeUrlKeyword.Any(x => str.ToLower().Contains(x))) 
3

您可以使用LINQ的AllAny方法來評估對數組元素的條件:

// Check for null/empty string, then ... 
var lower = str.ToLower(); 
if (excludeUrlKeyword.All(kw => !lower.Contains(kw))) { 
    ... 
} 

注意,這不是最快的方法:你會用正則表達式更好。作爲一個額外的好處,正則表達式可以防止「別名」,當你放棄一個關鍵字出現作爲長詞的一部分的字符串。

如果您想嘗試正則表達式的方式,從在配置文件中改變ExcludeUrlKeyword逗號分隔getmedia,cmsscripts,cmspages,asmx以豎線分隔getmedia|cmsscripts|cmspages|asmx,這樣你就可以直接將其以正則表達式:

var excludeUrlRegex = ConfigurationManager.AppSettings["ExcludeUrlKeyword"]; 
if (!Regex.IsMatch(str.ToLower(), excludeUrlRegex)) { 
    ... 
}