Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"); 
like image 208
nikorio Avatar asked Jan 02 '17 07:01

nikorio


2 Answers

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

like image 69
sujith karivelil Avatar answered Sep 30 '22 05:09

sujith karivelil


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

like image 33
shreesha Avatar answered Sep 30 '22 04:09

shreesha