Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

linq

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.

like image 929
Hcabnettek Avatar asked Nov 14 '12 15:11

Hcabnettek


2 Answers

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

if(!tmp.Select(x => x.Split('=')[0])
                    .Intersect(new[] { "foo", "baz" }, 
                               StringComparer.InvariantCultureIgnoreCase).Any())
    doSomething();
like image 199
L.B Avatar answered Nov 05 '22 05:11

L.B


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();
like image 21
Joshua Honig Avatar answered Nov 05 '22 06:11

Joshua Honig