简体   繁体   中英

How to use string.Contains for list of values

I have the following xmlnode (string) whose value would be of few given type ie:

"Ansi_nulls","Encrypted","Quoted_identifer" etc.

I want to test the xmlnode using xmlNode.Contains ("xxx","yyy") ..

What is the correct syntax ?

If you are testing the full (complete) value of the node, you can do it by reversing the call; check that a list of known values contains your current node value:

new[]{"Ansi_nulls","Encrypted","Quoted_identifer", ...}.Contains(xmlNode);

Contains takes a string to test for.

One way to solve your problem would be to use a simple regular expression

using System.Text.RegularExpressions;

if (Regex.IsMatch(nodevalue, "(Ansi_nulls|Encrypted|Quoted_identifer)")...
if (new[] {"xxx","yyy"}.Any(n => xmlNode.Contains(n)))

I would create an extension method using sehes solution:

    public static bool Contains(this string source, params string[] values)
    {
        return values.Any(value => source.Contains(value));
    }

That way you can call:

        xmlNode.Contains("string", "something else");

A simple if statement will work:

if (xmlNode.Contains("xxx") && xmlNode.Contains("yyy"))
{
// your work
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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