您可能想尝试LinqKit。有了这个库,你有一个PredicateBuilder
类方法:
public static Expression<Func<T, bool>> True<T>();
public static Expression<Func<T, bool>> False<T>();
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2);
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2);
这些是Expression
对象,这可以从lambda表达式可以轻松创建扩展。
有了这样一个表达式,你可以做yourDataSource.Where(expression)
。
对不起,对于C#表示法,我不知道VB.net ... 如果有人想修复它到VB,感觉自由。
编辑:
嘛,PredicateBuilder
只是一个整洁的语法糖。在他们的网站上你可以找到完整的源代码,这非常简单。不幸的是,在C#中。 这里有云:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
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.OrElse (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.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}
}
就是这样!表达式(在.net中是标准的,不需要额外的库)提供了一些很好的方法来处理它们,它们可以在where
子句中使用。 试试看吧:)
如果返回类型与上述查询相同,则使用传递的参数创建分离函数...请随时调用它... –