代码改变世界

拼linq 时网上整理的一个类

2013-08-23 10:34  sql_manage  阅读(157)  评论(0编辑  收藏  举报

public static class DynamicLinqExpressions
{
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>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
}

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
}

 

用法:

Expression<Func<DataRow, bool>> expressionResult = DynamicLinqExpressions.True<DataRow>();
if (!string.IsNullOrEmpty(staffName))
{
expressionResult.And(res => res.Field<string>("StaffName").Contains(staffName));
}
if (!string.IsNullOrEmpty(staffCode))
{
expressionResult.And(res => res.Field<string>("StaffCode")==staffCode);
}
if (!string.IsNullOrEmpty(staffAllPing))
{
expressionResult.And(res => res.Field<string>("StaffAllPing").Contains(staffAllPing));
}
if (!string.IsNullOrEmpty(staffShortPing))
{
expressionResult.And(res => res.Field<string>("StaffShortPing").Contains(staffShortPing));
}
if (!string.IsNullOrEmpty(selTopCompany) && selTopCompany!="-1")
{
expressionResult.And(res => res.Field<string>("CompanyUniqueCode") == selTopCompany);
}
if (!string.IsNullOrEmpty(selTopDepartment) && selTopDepartment!="-1")
{
expressionResult.And(res => res.Field<string>("DeptUniqueCode") == selTopDepartment);
}
if (!string.IsNullOrEmpty(selTopQuarter) && selTopQuarter!="-1")
{
expressionResult.And(res => res.Field<string>("QuartersUniqueCode") == selTopQuarter);
}
if (orderAscOrDesc == "DESC")
{
dataList = cacheList.AsQueryable().Where(expressionResult).OrderByDescending(row => row.Field<int>("StaffId")).Select(row => row).Skip(skipNum).Take(pageSize);
}
else
{
dataList = cacheList.AsQueryable().Where(expressionResult).OrderBy(row => row.Field<int>("StaffId")).Select(row => row).Skip(skipNum).Take(pageSize);
}
DataTable tempDt = new DataTable();
foreach (DataRow dtrow in dataList)
{
object[] o = dtrow.ItemArray;
DataRow dr= tempDt.NewRow();
dr = dtrow;
tempDt.Rows.Add(dr);
}
return new QueryResult();
}
catch (Exception ex)
{
throw ex;
}


}