这不是一篇完整的文章,只是一个速写。 但是我不能错过与人们分享这种见解的机会,因为它使我的编码生活变得更加美好
sooooooo容易得多。 http://www.albahari.com/nutshell/predicatebuilder.aspx它的用处取决于情况,但是当我构建搜索应用程序时,我发现它最有价值。 我不知道用户可能在搜索中包括哪些参数。 我不想用字符串构建一个select语句,因为我已经创建了LINQ to SQL类,并且我不想做
动态LINQ,因为对我而言,LINQ的重点是类型安全和IntelliSense。所以我找到了PredicateBuilder。 我最喜欢的部分是您不必下载并包含一些大型库。 您可以将几行代码粘贴到自己的项目中:
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);
}
}
添加一个名称空间并将其转储到您的项目中,您就可以使用它。
本文介绍了如何比我更好地使用它。 我确实发现了一种奇怪的行为:使用foreach循环。
您通常会这样做:
foreach(string s in stringCollection)
{
whereClause = whereClause.Or(p => p.SomeString == s);
}
但是,由于某种原因,它似乎将指针复制到“ s”或某物上,并且最终使用s的最后一个值获得了所有Or语句。
要解决此问题,请执行以下操作:
foreach(string s in stringCollection)
{
string temp = s;
whereClause = whereClause.Or(p => p.SomeString == temp);
}
除此之外,它效果很好。
From: https://bytes.com/topic/net/insights/887941-dynamic-linq-where-clauses-predicatebuilder