C# – Linq with String Array Contains

arraysclinqlinq-to-sql

I have a string array of items & a list of database objects and I want to do a select query out of it

List<string> target_terms = new List<string> { "car", "mechanic" }

if (isNotExactPhrase)
{
    List<int> _tagIds = (from item in dbContext.Tags
                    where target_terms.Any(w => item.TagName.Contains(w))
                    select item.TagId).ToList();
}

I want all tags with names in the array

I have to use 2 options I want to check Tagname contains any of the keyword &
If search is for exact phrase then I want to check any of the Tagname == any of the keyword

But for this query I am getting error

Local sequence cannot be used in LINQ to SQL implementations of query
operators except the Contains operator.

How to solve this?

Best Answer

Try this query

var _tagIds = (from item in dbContext.Tags
                    where keywords.contains(item.TagName)
                    select item.TagId).ToList();

There's no direct equivalent, but there are some methods work similarly, depending on the pattern.

string.Contains("pattern") is equivalent to LIKE '%pattern%'

string.StartsWith("pattern") is equivalent to LIKE 'pattern%'

string.EndsWith("pattern") is equivalent to LIKE '%pattern'