开发者

LINQ Multiple LIKE based on List

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?


This oughtta do it:

var query = table.Where(p => keywords.Any(kw => p.Name.StartsWith(kw)));


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜