问题
I have a list of keywords in an ArrayList and I wanted to be able to build a query to find records in a table based on this keywords.
Since the list of keywords is dynamic I cannot build a fixed query here.
I do something like this:
foreach (string kw in keywords)
{
query = query.Where(p => p.Name.StartsWith(kw));
}
The "StartsWith" is required here because I need to search those records that actually start with the provided keyword.
In T-SQL it Would be something like this
Select * from Table where
Name like 'keyword1%'
or Name like 'keyword2%'
or Name like 'keyword3%'
or ...
But I need to be able to do this in LINQ...Is this possible?
回答1:
This oughtta do it:
var query = table.Where(p => keywords.Any(kw => p.Name.StartsWith(kw)));
回答2:
var query = table.Where(p => keywords.Any(kw => p.Name.StartsWith(keyword1) || p.Name.StartsWith(keyword2) || p.Name.StartsWith(keyword3) || p.Name.StartsWith(keyword4)));
Hope it can help you and have a nice day.
来源:https://stackoverflow.com/questions/2921485/linq-multiple-like-based-on-list