改进的ExpressionItem扩展
using System;
using System.Linq.Expressions;
namespace Phoenix.Modules.Common.Infrastructure.TypeExtensions.LinqExtension
{
public static class ExpressionExtention
{
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, ExpressionItem<T> expressionItem)
{
//如果左边表达式为空
if (left == null)
{
left = (g => true);
return left.And(expressionItem);
}
//如果右表达式为空,返回左表达式
if (expressionItem == null)
{
return left;
}
//右边表达式变量值为空
if (expressionItem.Value == null)
{
//如果变量为空值不产生表达式
if (!expressionItem.AttachWhenValueNull) return left;
left = left.And(Specification<T>.Eval(expressionItem.Expression).GetExpression());
return left;
}
//如果右边表达式变量值不为空
Type t = expressionItem.Value.GetType();
//如果是字符型
if (t.Name == "String")
{
//如果是空白字符
if (string.IsNullOrWhiteSpace(expressionItem.Value))
{
//如果变量为空值不产生表达式
if (!expressionItem.AttachWhenValueNull) return left;
}
}
left = left.And(Specification<T>.Eval(expressionItem.Expression).GetExpression());
return left;
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, ExpressionItem<T> expressionItem)
{
//如果左边表达式为空
if (left == null)
{
left = (g => false);
return left.Or(expressionItem);
}
//如果右表达式为空,返回左表达式
if (expressionItem == null)
{
return left;
}
//右边表达式变量值为空
if (expressionItem.Value == null)
{
//如果变量为空值不产生表达式
if (!expressionItem.AttachWhenValueNull) return left;
left = left.Or(Specification<T>.Eval(expressionItem.Expression).GetExpression());
return left;
}
//如果右边表达式变量值不为空
Type t = expressionItem.Value.GetType();
//如果是字符型
if (t.Name == "String")
{
//如果是空白字符
if (string.IsNullOrWhiteSpace(expressionItem.Value))
{
//如果变量为空值不产生表达式
if (!expressionItem.AttachWhenValueNull) return left;
}
}
left = left.Or(Specification<T>.Eval(expressionItem.Expression).GetExpression());
return left;
}
}
public class ExpressionItem<T>
{
public ExpressionItem(Expression<Func<T, bool>> expression, dynamic value, bool attachWhenValueNull)
{
Expression = expression;
Value = value;
AttachWhenValueNull = attachWhenValueNull;
}
public Expression<Func<T, bool>> Expression { get; }
public dynamic Value { get; }
public bool AttachWhenValueNull { get; }
}
}