Linq query a string array in c# if contains either of two values?

14,478

Solution 1

Any better? I don't know but should work.

if(!tmp.Select(x => x.Split('=')[0])
                    .Intersect(new[] { "foo", "baz" }, 
                               StringComparer.InvariantCultureIgnoreCase).Any())
    doSomething();

Solution 2

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();

Solution 3

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();
Share:
14,478
Hcabnettek
Author by

Hcabnettek

@kettenbach

Updated on June 23, 2022

Comments

  • Hcabnettek
    Hcabnettek almost 2 years

    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.