jmasterx
jmasterx

Reputation: 54103

Query for string containing one or more of many strings

I found an example here:

var foo = things.Where(data => myList.Contains(data.Title));

However this is exact string matching. I am only interested in it if data.Title.ToLower() contains any of the strings found in list ToLower().

Say list has apple, book ClocK in it.

data.Title is for example: Apple Jacks, Book Club, Clockwork Book, those are all fine. But Claws and Foods, Clicks, Application Fundamentals, would not be accepted.

Upvotes: 3

Views: 95

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109079

You want to look for each item that the Title may contain (ignoring case):

var foo = things.Where(data => myList
                .Any(item => data.Title.ToLower().Contains(item.ToLower())));

Upvotes: 4

Tim S.
Tim S.

Reputation: 56536

var myList = new List<string> { "apple", "book", "ClocK" };
var things = new List<string> { "Apple Jacks", "Book Club", "Clockwork Book", "Claws and Foods", "Clicks", "Application Fundamentals" };
var myRegex = new Regex(string.Join("|", myList.Select(x => Regex.Escape(x))), RegexOptions.IgnoreCase);
foreach (var matchingThing in things.Where(x => myRegex.IsMatch(x)))
    Console.WriteLine(matchingThing);

Outputs:

Apple Jacks
Book Club
Clockwork Book

Upvotes: 1

Related Questions