c# - 如何从 Expression<Func<T>> 构建 Expression<Func<T,bool>>

标签 c# .net linq linq-expressions

有没有办法构建Expression<Func<T,bool>>来自 Expression<Func<T>>

例如类

public class MyClass
{
    public int Prop1{get;set;}
    public int Prop2{get;set;}
    public int Prop3{get;set;}
}

如果Expression<Func<T>>() => new MyClass{Prop2 = 5}那么结果应该是x => x.Prop2 == 5

如果Expression<Func<T>>() => new MyClass{Prop1 = 1, Prop3 = 3}那么结果应该是x => x.Prop1 == 1 && x.Prop3 == 3

换句话说,是否可以在运行时创建具有任意数量条件的函数?

最佳答案

像这样:

static Expression<Func<T,bool>> Munge<T>(Expression<Func<T>> selector)
{
    var memberInit = selector.Body as MemberInitExpression;
    if (memberInit == null)
        throw new InvalidOperationException("MemberInitExpression is expected");
    var p = Expression.Parameter(typeof(T), "x");

    Expression body = null;
    foreach (MemberAssignment binding in memberInit.Bindings)
    {
        var comparer = Expression.Equal(
            Expression.MakeMemberAccess(p, binding.Member),
            binding.Expression);
        body = body == null ? comparer : Expression.AndAlso(body, comparer);
    }
    if (body == null) body = Expression.Constant(true);

    return Expression.Lambda<Func<T, bool>>(body, p);
}

关于c# - 如何从 Expression<Func<T>> 构建 Expression<Func<T,bool>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13758539/

相关文章:

C# 私有(private)、静态和只读

.net - Dictionary<> 在顺序与随机上的表现

.net - IDisposable 对象是否意味着只创建和处理一次?

c# - 在某些行上使用.Distinct()

c# - 如何从一个xml文件中读取多个属性

c# - Oledb 阅读器无法正确读取 excel 文件

c# - 从用户控件访问表单

c# - 根据墨卡托投影的纬度计算 Y 位置

c# - 什么时候应该使用 HashSet<T> 类型?

c# - 基于 IEnumerable<string> 过滤项目