拼接LINQ動態表達式

using System;
using System.Linq;
using System.Linq.Expressions;

public static class LinqBuilder
{
    /// <summary>
    /// 默認True條件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static Expression<Func<T, bool>> True<T>() { return f => true; }

    /// <summary>
    /// 默認False條件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    /// <summary>
    /// 拼接 OR 條件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="exp"></param>
    /// <param name="condition"></param>
    /// <returns></returns>
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> exp, Expression<Func<T, bool>> condition)
    {
        var inv = Expression.Invoke(condition, exp.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>(Expression.Or(exp.Body, inv), exp.Parameters);
    }

    /// <summary>
    /// 拼接And條件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="exp"></param>
    /// <param name="condition"></param>
    /// <returns></returns>
    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> exp, Expression<Func<T, bool>> condition)
    {
        var inv = Expression.Invoke(condition, exp.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>(Expression.And(exp.Body, inv), exp.Parameters);
    }
}

public class Entity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Example
{
    public Example()
    {
        var linq = LinqBuilder.True<Entity>();
        linq.And(p => p.Id == 30);
        Expression<Func<Entity, bool>> condition = linq.Or(p => p.Name == "");
    }
}
相關文章
相關標籤/搜索