如何撰写现有的Linq表达式 [英] How do I compose existing Linq Expressions

查看:53
本文介绍了如何撰写现有的Linq表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想组成两个Linq表达式的结果.它们以以下形式存在

I want to compose the results of two Linq Expressions. They exist in the form

Expression<Func<T, bool>>

因此,我想组成的两个对象本质上都是一个参数(类型T)的委托,它们都返回一个布尔值.我想组成的结果将是布尔值的逻辑评估.我可能会将其实现为扩展方法,因此我的语法将类似于:

So the two that I want to compose are essentially delegates on a parameter (of type T) that both return a boolean. The result I would like composed would be the logical evaluation of the booleans. I would probably implement it as an extension method so my syntax would be something like:

Expression<Func<User, bool>> expression1 = t => t.Name == "steve";
Expression<Func<User, bool>> expression2 = t => t.Age == 28;
Expression<Func<User, bool>> composedExpression = expression1.And(expression2);

然后在我的代码中,我要评估组成的表达式

And later on in my code I want to evaluate the composed expression

var user = new User();
bool evaluated = composedExpression.Compile().Invoke(user);

我提出了一些不同的想法,但我担心它比我希望的要复杂.怎么做?

I have poked around with a few different ideas but I fear that it is more complex than I had hoped. How is this done?

推荐答案

以下是示例:

var user1 = new User {Name = "steve", Age = 28};
var user2 = new User {Name = "foobar", Age = 28};

Expression<Func<User, bool>> expression1 = t => t.Name == "steve";
Expression<Func<User, bool>> expression2 = t => t.Age == 28;

var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());

var result = Expression.Lambda<Func<User, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);

Console.WriteLine(result.Compile().Invoke(user1)); // true
Console.WriteLine(result.Compile().Invoke(user2)); // false

您可以通过扩展方法重用此代码:

You can reuse this code via extension methods:

class User
{
  public string Name { get; set; }
  public int Age { get; set; }
}

public static class PredicateExtensions
{
  public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,Expression<Func<T, bool>> expression2)
  {
    InvocationExpression invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());

    return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
  }
}

class Program
{
  static void Main(string[] args)
  {
    var user1 = new User {Name = "steve", Age = 28};
    var user2 = new User {Name = "foobar", Age = 28};

    Expression<Func<User, bool>> expression1 = t => t.Name == "steve";
    Expression<Func<User, bool>> expression2 = t => t.Age == 28;

    var result = expression1.And(expression2);

    Console.WriteLine(result.Compile().Invoke(user1));
    Console.WriteLine(result.Compile().Invoke(user2));
  }
}

这篇关于如何撰写现有的Linq表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆