Click here to Skip to main content
15,888,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, my Linq learning continues, say I have a List containing
C#
{"Pete","Lynne"};

and a string containing
C#
"This is a string and may or may not contain a word we are looking for like Pete"

How can I search the string for any word in my list ?

What I have tried:

Googling but only found examples that search lists not the string
Posted
Updated 27-Mar-16 1:14am

C#
string input = "This is a string and may or may not contain a word we are looking for like Pete";
List<string> search = new List<string>() { "Pete", "Lynne"};
bool found = input.Split(' ').Any(x => search.Contains(x));

It works like this: the string gets split into an array of words. Then Any checks whether there is an x in this array where search.Contains(x).

Enumerable.Any(TSource) Method (IEnumerable(TSource)) (System.Linq)[^]
 
Share this answer
 
Comments
pkfox 27-Mar-16 8:05am    
Thanks very much - I now have two ways of doing it ( I'm sure there are more )
Thomas Daniels 27-Mar-16 8:19am    
You're welcome!
I think you meant it the other way around, like this:
C#
string input = "This is a string and may or may not contain a word we are looking for like Pete";
List<string> search = new List<string>() { "Pete", "Lynne" };
bool found = search.Any(s => input.Contains(s));

The last line is equivalent to:
C#
bool found = search.Where(s => input.Contains(s)).Any();
 
Share this answer
 
Comments
pkfox 27-Mar-16 8:03am    
Thanks very much I always forget you can point the output to another object
Sascha Lefèvre 27-Mar-16 10:12am    
;-)
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900