您可能想嘗試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
子句中使用。 試試看吧:)
如果返回類型與上述查詢相同,則使用傳遞的參數創建分離函數...請隨時調用它... –