C#中的表达式

编程入门 行业动态 更新时间:2024-10-15 08:22:09
本文介绍了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#中的表达式

本文发布于:2023-11-06 08:09:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563152.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!