Z Daneshi
Z Daneshi

Reputation: 57

How to search any items of a list within a string using Linq

I am going to write search query. In that query I have a list of string like this:

var listWords=new List<string>(){"Hello","Home","dog","what"};

and also I have list of customers. How Can I search if customer's Name contains at least one of items in listWords:

Tried:

var prodList = events.Where(x =>listWords.IndexOf(x.Name.Trim().ToLower()) != -1).ToList();

Upvotes: 1

Views: 92

Answers (1)

Gilad Green
Gilad Green

Reputation: 37281

Use .Where and .Any:

var result = events.Where(c => listWords.Any(w => c.Name.Contains(w)));

Problem with your solution is that you are converting your string to lower case but the collection of words has characters in upper case. In that case it will not find a match: How can I make Array.Contains case-insensitive on a string array?

Upvotes: 4

Related Questions