将2个参数Lambda表达式转换为1个参数Lambda表达式(指定一个参数)

编程入门 行业动态 更新时间:2024-10-19 08:54:56
本文介绍了将2个参数Lambda表达式转换为1个参数Lambda表达式(指定一个参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有表情

Expression<Func<Car, Driver, bool>> CanBeDrivenBy = (car, driver) => car.Category == 'B' && driver.Age > 18;

我想得到可以由某些驾驶员驾驶的汽车

and I want to get cars which can be driven by some driver

IQueryable<Cars> cars = ...; Driver driver = ...; cars.Where(CanBeDrivenBy); // Fail, expecting Expression<Func<Car, bool>>

所以我需要将Expression<Func<Car, Driver, bool>>转换为Expression<Func<Car, bool>>(指定驱动程序)

So I need to convert Expression<Func<Car, Driver, bool>> to Expression<Func<Car, bool>> (specify driver)

是的,我可以使用

cars.Where(c => c.Category == 'B' && driver.Age > 18);

但是我需要可以动态更改表达式的解决方案.而且我需要通过表达式(使用实体框架)

but I need solution with expression which can be changed dynamicly. And I need to pass Expression (using entity framework)

推荐答案

此工作

我编写了此函数,通过指定第二个参数来将参数数量从2减少到1.

I wrote this function to reduce number of arguments from 2 to 1 by specifying the second argument.

public static Expression<Func<T1, TResult>> Bind2nd<T1, T2, TResult>(Expression<Func<T1, T2, TResult>> source, T2 argument) { Expression arg2 = Expression.Constant(argument, typeof(T2)); var arg1 = Expression.Parameter(typeof(T1)); return Expression.Lambda<Func<T1, TResult>>(Expression.Invoke(source, arg1, arg2), arg1); }

用法:

IQueryable<Car> cars = ...; Driver driver = ...; cars.Where(Bind2nd(CanBeDrivenBy, driver));

arg1是通话之间的临时存储.

arg1 is temporary storage between calls.

有任何等效的系统功能吗?

Is there any system equivalent function?

更多推荐

将2个参数Lambda表达式转换为1个参数Lambda表达式(指定一个参数)

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

发布评论

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

>www.elefans.com

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