lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>区别

前言:

自己通过lambda表达式的封装,将对应的表达式转成字符串的过程中,对lambda表达式有了新的认识

原因:

很多开发者对lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>表示存在疑惑,现在就用代码举个简单列子

 

 

 

 原代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Lambda
{
class Program
{
static void Main(string[] args)
{
Expression<Func<Person, bool>> exp = null;

Func<Person, string> func = null;
func = p => { return p.age; };

exp = p => p.sex=="男";

Person person = new Person();
person.age = "12";
person.name = "zouhp";
person.sex = "男";

Console.WriteLine(exp);
Console.WriteLine(exp.Compile()(person));
Console.WriteLine(func(person));
Console.ReadLine();
}
public class Person
{
public string name;
public string age;
public string sex;
}
}
}

 

结论:

Func<TObject, bool>是委托(delegate)

Expression<Func<TObject, bool>>是表达式

Expression编译后就会变成delegate,才能运行。比如

Expression<Func<int, bool>> ex = x=>x < 100;

Func<int, bool> func = ex.Compile(); 

然后你就可以调用func:

func(5) //-返回 true

func(200) //- 返回 false

而表达式是不能直接调用的。

参考:http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct

 

关于EF中用哪个你可以看看这篇文章:Entity Framework - Func引起的数据库全表查询

关于如何将多个expression合并为一个可以写多个where:

.where(expression1).where(expression2)...

运行时EF会自动合并优化的

转载于:https://www.cnblogs.com/zouhp/p/7188904.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值