对于我正在做的网站,我们正在使用LINQ to Entities.我被指控为网站添加搜索功能.我试图找出在数据库中的单个字段上搜索多个关键字(用户输入)的最优雅方式.请允许我举个例子.
表列:
Name, Description
示例行:
"Cookie monster", "Fluffy, likes cookies and blue"
用户搜索(分隔符无关紧要):
"blue fluffy"
目前我正在使用以下内容:
public ListSearchByKeywords(string keywords) { List output = new List (); string[] k = keywords.ToLower().Split(' '); using (SesameStreet_Entities entities = new SesameStreet_Entities()) { IQueryable filter = entities.SesameCharacters; foreach (string keyword in k) filter = ForceFilter(filter, keyword); output = filter.ToList(); } return output; } private IQueryable ForceFilter(IQueryable filter, string keyword) { return filter.Where(p => p.Description.ToLower().Contains(keyword)); }
这目前按预期工作,但我认为这不是问题的最佳解决方案.我错过了一些明显的东西吗?
注意:这是AND
匹配的.
我发现这对我有用 - 这是使用VB.Net与Entity Framework 4.0,但我确信原理翻译.
这个执行"OR"样式查询:
Function Search(ByVal query As String) As IQueryable(Of Product) Dim queryWords As String() = query.Split() Dim entities As New Entities() Return entities.Products.Where(Function(p) queryWords.Any(Function(w) p.Description.Contains(w))) End Function
这个人做"和"风格的查询:
Function Search(ByVal query As String) As IQueryable(Of product) Dim queryWords As String() = query.Split() Dim entities As New Entities() Return entities.Products.Where(Function(p) queryWords.All(Function(w) p.Description.Contains(w))) End Function