码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-16 10:01:32      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:compile   person   eric   png   9.png   arch   委托   lin   简单   

前言:

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

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

标签:compile   person   eric   png   9.png   arch   委托   lin   简单   

原文地址:http://www.cnblogs.com/zouhp/p/7188904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!