码迷,mamicode.com
首页 > 其他好文 > 详细

拼接LINQ动态表达式

时间:2016-07-12 17:27:49      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

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 == "");
    }
}

 

拼接LINQ动态表达式

标签:

原文地址:http://www.cnblogs.com/magic_evan/p/5664015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!