LINQ Multiple LIKE based on List

为君一笑 提交于 2020-07-15 06:18:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!