'LINQ select column that contains some array element
I have a field "details" varchar(MAX) in my table with the detailed description of an item, I need to select the records that contain the keywords passed by the user in a string array.
var searchTerms = new List<string> { "car", "black", "bike", "blue" };
I tried to do it like this:
var result = (from i in _contexto.itens
where searchTerms.Any(d => i.details.Contains(d))
select i.id);
and I get the following error:
The LINQ expression 'DbSet() .Where(i => __searchTerms_0 .Any(d => i.details.Contains(d)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
I also tried this link's approach using the "SearchExtensions nuget package" and the same error occurs.
How can I do this? or should I make a query for each item in the array?
Example of a text I want to search for:
It is a long established fact that a car will be distracted by the readable content of a page when looking at its bike. The point of using Lorem Ipsum is that it has a more-or-less normal distribution
Thanks!
Solution 1:[1]
var searchTerms = new List<string> { "car", "black", "bike", "blue" };
string examplestring = "It is a long established fact that a car will be distracted by the readable content of a page when looking at its bike. The point of using Lorem Ipsum is that it has a more-or-less normal distribution";
var result = searchTerms.Select(s => (examplestring.Contains(s)) ? (object)searchTerms.IndexOf(s) : null).Where(w => w != null).ToList();
Solution 2:[2]
Adapting Alexander's advice from the link you gave, for your situation:
var searchTerms = new List<string> { "car", "black", "bike", "blue" };
Expressions<Func<TYPE_OF_OBJECT_IN_ITENS_HERE, bool>> expression = it => false;
foreach(var searchTerm in searchTerms)
{
expression = expression.Or(it => it.details.Contains(searchTerm));
}
var result = _contexto.itens.Where(expression);
You didn't post any detail about the type of object inside itens, so you'll have to replace that above
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | once ng kahirapan |
| Solution 2 | Caius Jard |
