简体   繁体   English

Linq在C#中查询字符串数组是否包含两个值之一?

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

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. 如果foo中的所有字符串都不包含“ bar”或“ baz”,我想执行一些代码。 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. ***还请注意,tmp中的值类似于"bar=someValue"如查询字符串。 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 : 您可以使用嵌套的AnyIndexOf StringComparison重载:

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

I don't think there is anything wrong with your existing code; 我认为您现有的代码没有任何问题; though it could be slightly modified to avoid an extra ToLower() call: 尽管可以稍加修改以避免额外的ToLower()调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM