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会自动合并优化的

posted @ 2017-07-16 00:34  zouhp  阅读(2045)  评论(0编辑  收藏  举报