Chris Stewart
Chris Stewart

Reputation: 3299

LINQ query for full text searching

How can I query a collection for a keyword like "John Doe" where the value of a property might be "John M Doe"? Doing a contains certainly will not work but below is an idea of what I'm after. people, for reference, is a List containing Person objects that have Name and Description properties.

string keyword = "John Doe";
var q = from person in people
        where person.Name.ToLower().Contains(keyword.ToLower()) || person.Description.ToLower().Contains(keyword.ToLower())
        select person;

Upvotes: 1

Views: 2270

Answers (3)

Mau
Mau

Reputation: 14478

bool MatchKeywords(string keyWord, string text) {
    var tokens = keyWord.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries).Select(s=>s.Trim().ToLower());
    return tokens.Any(t => text.ToLower().Contains(t));
}


//...

string keyword = "John Doe";

var q = from person in people
        where MatchKeywords(keyword, person.Name)
        select person;

Upvotes: 1

Samuel Jack
Samuel Jack

Reputation: 33300

This sounds like a case for Linq to Lucene

Upvotes: 1

LBushkin
LBushkin

Reputation: 131806

You could try dividing the search term into tokens and searching for them individually, but this will only go so far - it won't handle more complex variations. You may be able to craft a regular expression, but that too won't necessarily catch more complex cases.

If you need something more than trivial matching support, you may want to look into Lucene.NET, which has a richer set of comparison and search functions. Lucene include some support for Linq, so that may allow you to maintain some of your queries.

Upvotes: 0

Related Questions