Reputation: 12928
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.
Upvotes: 6
Views: 15111
Reputation: 39085
I don't think there is anything wrong with your existing code; though it could be slightly modified to avoid an extra ToLower()
call:
var exists = tmp.Any(p =>
{
var s = p.ToLower();
return s.Contains("bar") || s.Contains("baz");
});
if(!exists) doSomething();
If your search terms can be numerous, something like this might work better:
var terms = new string[] {"bar", "baz", "foo", "boo", ...};
var exists = tmp.Any(p => terms.Any(t => p.ToLower().Contains(t)));
if(!exists) doSomething();
Upvotes: 1
Reputation: 13215
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();
Upvotes: 1
Reputation: 116138
Any better? I don't know but should work.
if(!tmp.Select(x => x.Split('=')[0])
.Intersect(new[] { "foo", "baz" },
StringComparer.InvariantCultureIgnoreCase).Any())
doSomething();
Upvotes: 4