2

I've got a string array that looks like this:

string[] userFile = new string[] { "JohnDoe/23521/1", "JaneDoe/35232/4", ... };

I'm trying the following but this will only return exact matches. I want to be able to return a match if I am searching for "23521".

var stringToCheck = "23521";

if (userFile.Any(s => stringToCheck.Contains(s)))
{
    // ...

4 Answers 4

8

Your Contains() call should be the other way round:

if (userFile.Any(s => s.Contains(stringToCheck)))

You want to check whether any string s in your userFile string array contains stringToCheck.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Can I now select the whole string and then check if the third item in the string (the number after the second delimiter) is equal to a value.
Can you clarify your question? Not sure what you mean - or do you mean just if(userFile[2] == stringToCheck) ?
if (userFile.Any(s => stringToCheck.Contains(s))) ... if yes now check if the number after the second "/" in "JohnDoe/23521/1" is for example greater than 0 and then put that number into a variable.
You have to iterate over the items that fit the condition - foreach(var matchingItem in userFile.Where(s => stringToCheck.Contains(s))) then you can use matchingItem.Split('/') - look up the methods on msdn
1

if (userFile.Any(s => s.Contains(stringToCheck)))

Comments

1

You want to check if the string in the array contains the check string, not the other way around:

userFile.Any(s => s.Contains(stringToCheck))

Comments

1

The following seems like a better choice:

if (userFile.Any(s => s.Contains(stringToCheck)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.