lambda表達式Expression > 、Func 區別


前言:

自己通過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會自動合並優化的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM