1

I have following if condition:

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

I am trying to create an array of keywords instead of putting multiple AND conditions, could you please help?

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

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

How to build the same if condition from the array?

2
  • Use LinQ Any or All Commented Aug 3, 2017 at 11:52
  • can we write without LINQ ? Commented Aug 3, 2017 at 13:19

2 Answers 2

3

You can use LINQ's All or Any method to evaluate a condition on array elements:

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

Note that this is not the fastest approach: you would be better off with a regex. As an added bonus, regex would prevent "aliasing", when you discard a string with a keyword appearing as part of a longer word.

If you would like to try regex approach, change ExcludeUrlKeyword in the config file from comma-separated getmedia,cmsscripts,cmspages,asmx to pipe-separated getmedia|cmsscripts|cmspages|asmx, so that you could feed it directly to regex:

var excludeUrlRegex = ConfigurationManager.AppSettings["ExcludeUrlKeyword"];
if (!Regex.IsMatch(str.ToLower(), excludeUrlRegex)) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Linq Any should do this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.