I have an array of strings
string[] tmp = foo();
If NONE of the strings in foo contain either "bar" or "baz" I want to execute some code. Is this the proper way to query this object?
if(!tmp.Any(p => p.ToLower().Contains("bar") || p.ToLower().Contains("baz"))
doSomething();
The || seems silly. Should I be using a regular expression here or is there an even better way to be doing this? ***Also note the values in tmp are like "bar=someValue"
like a query string. This code works ok but I'm certain it can written better. Thanks for any tips of feedback.
Any better? I don't know but should work.
if(!tmp.Select(x => x.Split('=')[0])
.Intersect(new[] { "foo", "baz" },
StringComparer.InvariantCultureIgnoreCase).Any())
doSomething();
You can use nested Any
with StringComparison
overload of IndexOf
:
string[] source = { "hi=there", "hello=world", "foo=bar" };
string[] exclude = { "baz", "bar" };
if (!source.Any(src =>
exclude.Any(exl =>
src.IndexOf(exl, StringComparison.InvariantCultureIgnoreCase) >= 0)))
doSomething();
Or packaged as an extension method:
public static class StringExtensions {
public static bool ContainsAny(
this IEnumerable<string> source,
IEnumerable<string> target,
StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase) {
return source.Any(xsource => target.Any(
xtarget => xsource.IndexOf(xtarget, comparisonType) >= 0));
}
}
// Later ...
if (!source.ContainsAny(exclude))
doSomething();
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