Home > OS >  LINQ select column that contains some array element
LINQ select column that contains some array element

Time:05-07

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!

CodePudding user response:

var result = _contextto
    .itens
    .Where(i => searchTerms.Any(t => i.details.Contains(t))
    .Select(i => i.id)
    .ToList();

CodePudding user response:

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();

CodePudding user response:

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

  • Related