Benehmb
Benehmb

Reputation: 15

C# Linq All in Where condition

I had the following LinqExpression:

var results = _localDatabase.Table<ArticleData>()
                            .Where(article => article.ArticleName!.ToLower().Contains(searchQuery.ToLower());

Which had the disadvantage, that the text that has been searched had to be part of the ArticleName. But sometimes, users only enter parts of words (ArticleName is "Spider-Man: Across the Spider-Verse" and users search for "man" and "verse").

So I split the search query in individual parts:

string[] splitQuery = searchQuery.Split(' ');

And tried to search for the individual parts:

var results = _localDatabase.Table<ArticleData>()
                            .Where(article => splitQuery.All<string>(queryPart => article.ArticleName!.Contains(queryPart)));

Which in theory, sounded great, but in practice, I got an error

Cannot compile: Lambda

TLDR

I need a way to pack something like this all method, or something like this into the linq expression.

Edit

I have a SQLite database. With _localDatabase.Table<ArticleData>(), I get a queryable object.

Upvotes: -1

Views: 123

Answers (1)

SomeBody
SomeBody

Reputation: 8743

You can use an individual Where clause for each item in splitQuery:

var query = _localDatabase.Table<ArticleData>().AsQueryable();

foreach (var item in splitQuery)
{
    query = query.Where(article => article.ArticleName!.ToLower().Contains(item.ToLower()));
}

query = query.Skip(startIndex ?? 0).Take(requestedNumberOfItems ?? 5);
var result = query.ToList();

Upvotes: 0

Related Questions