您需要構建一個表達式樹來表示您感興趣的所有條件,並結合Expression.OrElse
,然後在最後一次調用Where
。
如果您當前的來源是匿名類型,這可能有點棘手,但否則應該不會太糟糕。這裏有一個例子 - 可能有更簡單的參數替換方法,但這並不算太壞。 (雖然只ExpressionVisitor
.NET 4的工作......你必須執行類似的東西自己,如果你想使用這個在.net 3.5)。
using System;
using System.Linq;
using System.Linq.Expressions;
public class Test
{
static void Main()
{
IQueryable<string> strings = (new[] { "Jon", "Tom", "Holly",
"Robin", "William" }).AsQueryable();
Expression<Func<string, bool>> firstPredicate = p => p.Contains("ll");
Expression<Func<string, bool>> secondPredicate = p => p.Length == 3;
Expression combined = Expression.OrElse(firstPredicate.Body,
secondPredicate.Body);
ParameterExpression param = Expression.Parameter(typeof(string), "p");
ParameterReplacer replacer = new ParameterReplacer(param);
combined = replacer.Visit(combined);
var lambda = Expression.Lambda<Func<string, bool>>(combined, param);
var query = strings.Where(lambda);
foreach (string x in query)
{
Console.WriteLine(x);
}
}
// Helper class to replace all parameters with the specified one
class ParameterReplacer : ExpressionVisitor
{
private readonly ParameterExpression parameter;
internal ParameterReplacer(ParameterExpression parameter)
{
this.parameter = parameter;
}
protected override Expression VisitParameter
(ParameterExpression node)
{
return parameter;
}
}
}
正是我需要的:D – 2013-03-26 14:47:17
Replacer究竟在幹什麼? – seebiscuit 2014-09-05 20:38:37
@Seabiscuit:它基本上使所得到的表達式樹中的所有參數表達式指向相同的參數表達式,而不是針對頂層和每個「子表達式」分別表示。 – 2014-09-05 20:42:41