0

how to search string str = "three"; in list List = new List<string> { "line one", "line two", "line three", "line four", "row three", "linethree", "three" }; to get this result:

line three 
row three 
three
0

3 Answers 3

1

Split each string with space and check if any splited string equals to your target string. Here is the code:

var list = new List<string> { "line one", "line two", "line three", "line four", "row three", "linethree", "three" };

var result = list.Where(i => i.Split(' ').Any(j => j.Equals("three"))).ToList();

//result:
//    line three 
//    row three 
//    three

Also you may want to use StringComparison.InvariantCultureIgnoreCase as the second parameter of the Equals method in the case that you are looking for case-insensitive solution.

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

Comments

0

add space at the first of three like this:

string str = " three"

so it just get words

and for updated input use like this

string str = " "+"three"

3 Comments

hi, yes but I'm not sure if can use it this way with updated list and inputs
@LadO it work before any word have space so in just get words try it it work
thank you for your answer, yes this way it can be done, but for my particular case answer of Hossein Narimani Rad is more suitable
0

Convert str to regex pattern by adding \b at beginning and end to find words then use Regex.Match to select the matches.

Comments

Your Answer

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