peirix
peirix

Reputation: 37751

filtering a sublist of strings in C#

I have an object which looks something like this

class MyObject
{
    string Name;
    string Description;
    List<string> Keywords;
}

And when I'm searching through these, I have a List<MyObject> AllObjects, which I want to filter based on the Keywords

var query = Request["q"];
//will only return exact matches
var exactHits = GetAll().Where(x => x.Keywords.Contains(query));
//I want something like this
var searchHits = GetAll().Where(x => x.Keywords.Contains(Regex.Match(query)));

Upvotes: 1

Views: 309

Answers (2)

Petar Ivanov
Petar Ivanov

Reputation: 93030

Regex reg = new Regex(query);
var searchHits = GetAll().Where(x => x.Keywords.Any(k => reg.IsMatch(k)));

Upvotes: 1

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

Not 100% sure of the Regex.Match syntax, but it should be something like this:

var searchHits = GetAll().Where(x => x.Keywords.Any( k => Regex.Match(k, query).Success));

This will return all MyObjects where at least one of the keywords matches the query regex.

Upvotes: 1

Related Questions