您的位置:首页 > 其它

Linq动态查询之Expressions扩展PredicateExtensions

2010-07-19 17:11 387 查看
本文大部分内容来自肖坤的《Linq动态查询与模糊查询》。以下是PredicateExtensions的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
/// <summary>
/// 构造函数使用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混合时写在AND后的OR有效
/// 构造函数使用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混合时写在OR后面的AND有效
/// </summary>
public static class PredicateExtensions
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
{
var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
{
var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
}
}


以下是示例:

void DataBind1()
{
string strSearch = Request.QueryString["search"] == null ? "" : Request.QueryString["search"];
Expression<Func<table1, bool>> searchPredicate = t => true;
searchPredicate = PredicateExtensions.True<table1>();
if (strSearch.Length > 0)
{
searchPredicate = searchPredicate.And(t => t.title.Contains(strSearch));
searchPredicate = searchPredicate.Or(t => t.cnt.Contains(strSearch));
txtSearch.Text = strSearch;
}
IQueryable ds = _db.table1.Where(searchPredicate).OrderByDescending(t => t.id);
ListView1.DataSource = ds;
ListView1.DataBind();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: