You can define your own string.ContainsAny()
and string.ContainsAll()
methods. As a bonus, I've even thrown in a string.Contains()
method that allows for case-insensitive comparison, etc.
public static class Extensions
{
public static bool Contains(this string source, string value, StringComparison comp)
{
return source.IndexOf(value, comp) > -1;
}
public static bool ContainsAny(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.Any(value => source.Contains(value, comp));
}
public static bool ContainsAll(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.All(value => source.Contains(value, comp));
}
}
You can test these with the following code:
public static void TestExtensions()
{
string[] searchTerms = { "FOO", "BAR" };
string[] documents = {
"Hello foo bar",
"Hello foo",
"Hello"
};
foreach (var document in documents)
{
Console.WriteLine("Testing: {0}", document);
Console.WriteLine("ContainsAny: {0}", document.ContainsAny(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine("ContainsAll: {0}", document.ContainsAll(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine();
}
}