简体   繁体   中英

How to check if string contains list value and separately if contains but with other value

I'm trying to figure out how to define if string contains/does not contains list value and if contains but with other value.

If I have input string:

string inputString = "it was one";

and I want find specific value for condition:

var numbList = new List<string> {"zero", "one", "two"}; 

if (!numbList.Any(inputString.Contains)) 
{
     Console.WriteLine("string does not contains list value");                                           
}
else
{
     Console.WriteLine("string contains list value"); 
}

But not sure what is a proper way if I want to know also about third condition, if string contains value but also contains other words.

For string: inputString = "it was one"; desired result should be:

 Console.WriteLine("string contains list value and other words"); 

for string: inputString = "one";

 Console.WriteLine("string contains list value"); 

and for: inputString = "it was";

 Console.WriteLine( "string does not contains list value"); 

I think you are looking for something like this:

if (inputString.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries).All(x => numbList.Contains(x)))
{
    opDisplay="string contains list value";
}
else if (numbList.Any(x => inputString.Contains(x)))
{
    opDisplay = "string contains list value and other words";
}
else
{
    opDisplay = "string does not contains list value";
}

You can try an example here

why not use below code? i can not think of one condition where it fails.

            string inputString = "it was one ";
            var numbList = new List<string> { "zero", "one", "two" };
            if (numbList.Any(x => inputString.Contains(x)))
            {
                if (numbList.Any(x => inputString.Trim().StartsWith(x) && inputString.Trim().EndsWith(x)))
                {
                    Console.WriteLine("string contains list value");
                }
                else
                {
                    Console.WriteLine("string contains list value and other words");
                }
            }
            else
            {
                Console.WriteLine("string does not contains list value");
            }

find the fiddle here

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