Linq to Sql任何关键字搜索查询 [英] Linq to Sql any keyword search query
问题描述
我的应用程序中有一种情况,用户可以搜索术语列表.搜索需要按以下顺序进行三遍:
I have a case in my application where the user can search for a list of terms. The search needs to make three passes in the following order:
- 一个用于完全匹配他们输入的内容.完成,轻松.
- 所有单词(分别)匹配的地方.完成,也很容易.
- 其中任何单词匹配的地方……如何?
- One for an exact match of what they entered. Done, easy.
- One where all the words (individually) match. Done, also easy.
- One where any of the words match...how?
从本质上讲,在Linq to Sql中,我该如何执行以下操作:
Essentially, how do I, in Linq to Sql, tell it to do this:
select * from stuff s where s.Title like '%blah%' || s.Title like '%woo&' || s.Title like '%fghwgads%' || s.Title like...
以此类推?
推荐答案
这可能很困难...我认为您必须编写自己的运算符.
This might be a tough one... I think you'd have to write your own operator.
(更新:是的,我测试了它,它可以正常工作.)
(Update: Yep, I tested it, it works.)
public static class QueryExtensions
{
public static IQueryable<TEntity> LikeAny<TEntity>(
this IQueryable<TEntity> query,
Expression<Func<TEntity, string>> selector,
IEnumerable<string> values)
{
if (selector == null)
{
throw new ArgumentNullException("selector");
}
if (values == null)
{
throw new ArgumentNullException("values");
}
if (!values.Any())
{
return query;
}
var p = selector.Parameters.Single();
var conditions = values.Select(v =>
(Expression)Expression.Call(typeof(SqlMethods), "Like", null,
selector.Body, Expression.Constant("%" + v + "%")));
var body = conditions.Aggregate((acc, c) => Expression.Or(acc, c));
return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
}
然后您可以通过以下方式调用它:
Then you could call this with:
string[] terms = new string[] { "blah", "woo", "fghwgads" };
var results = stuff.LikeAny(s => s.Title, terms);
P.S.您需要将System.Linq.Expressions
和System.Data.Linq.SqlClient
命名空间添加到QueryExtensions
类的命名空间中.
P.S. You'll need to add the System.Linq.Expressions
and System.Data.Linq.SqlClient
namespaces to your namespaces for the QueryExtensions
class.
这篇关于Linq to Sql任何关键字搜索查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!