C#中的表达式 [英] Expressions in C#

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

问题描述

大家好,

如何转换为Func返回类型?

在下面的代码中,我在提到错误"的地方出现错误.因为我无法从Employee的IEnumerable转换为Expression< Func< Employee>>.我该如何转换呢?

公共静态类PredicateClass
{
    公共静态表达式< Func< List< Employee>>> GetByDeptId(int deptId)
    {
      雇员obj = new Employee();
      return obj.GetAllEmployees().Where(x => x.DeptId == deptId); //错误
    }
}

班级计划
{

静态void Main(string [] args)
{
  PredicateClass.GetByDeptId(2); //错误
} 


解决方案

重要的是要认识到Expression和IEnumerable是两个完全不同的东西,所以您不能只是转换". >

表达式是给定表达式的树数据结构的表示.在您的特定情况下,该函数的数据结构将返回雇员列表.

换句话说,它描述的是函数的功能,而不是实际执行的功能.

也就是说,要返回一个表示您的函数的表达式,那么我认为您可以这样做:

返回()=> obj.GetAllEmployees().其中​​(x => x.DeptId == deptId); 

(您可能需要在该return语句的末尾粘贴一个'.ToList()').


Hi All,

How do I convert to Func return type?

In the below code I get error in the places where I have mentioned "Error" because I am not able to convert from IEnumerable of Employee to Expression<Func<Employee>>. How do I convert to that?

public static class PredicateClass
{
    public static Expression<Func<List<Employee>>> GetByDeptId(int deptId)
    {
      Employee obj = new Employee();
      return obj.GetAllEmployees().Where(x=>x.DeptId == deptId); // Error
    }
}

class Program
{

static void Main(string[] args)
{ 
  PredicateClass.GetByDeptId(2); // Error 
}


解决方案

It's important to recognise that an Expression and and an IEnumerable are two completely different things so you cannot just 'convert'.

The Expression is a representation of the tree data structure for a a given expression. In your particular case, a data structure for a function that returns a list of Employees.

In other words, it describes what the function does rather than actually doing it.

That said, to return an expression representing your function then I think you could do:

return ()=>obj.GetAllEmployees().Where(x=>x.DeptId == deptId); 

(You may need to stick a '.ToList()' on the end of that return statement).


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

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