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

Question

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

Answers 2
Added at 2017-01-02 08:01
Tags
Question

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"); 
Answers to

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

nr: #1 dodano: 2017-01-02 08:01

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

nr: #2 dodano: 2017-01-02 09:01

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

Source Show
◀ Wstecz