|
★☆☆☆☆☆☆☆☆☆ |
积分:285 |
发帖:317 |
登录:2024/3/26 |
注册:2006/6/28 |
|
(1楼)【原创】终于完成了LINQ to SQL的多字段多关键词搜索功能
调用方法如下: var query = db.T_Article.Where(t=>t.IsAudit);
query = Search(query, t=>new{t.Title, t.Content}, new[]{"key1", "key2"}); 代码如下(记得using System.Linq.Expressions) IQueryable<MyTable> Search<MyTable, MyField>(IQueryable<MyTable> query, Expression<Func<MyTable, MyField>> arrField, string[] arrKeyword)
{
Expression rule = null;
foreach (var strKey in arrKeyword)
{
if (strKey.Trim() == "") continue;
foreach (var field in ((NewExpression)arrField.Body).Arguments)
{
var expr = Expression.Call(field, typeof(string).GetMethod("Contains"), Expression.Constant(strKey));
if (rule == null)
{
rule = expr;
continue;
}
rule = Expression.Or(rule, expr);
}
}
if (rule == null) return query;
return query.Where((Expression<Func<MyTable, bool>>)Expression.Lambda(rule, arrField.Parameters[0]));
}
|