zoukankan      html  css  js  c++  java
  • 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会自动合并优化的

  • 相关阅读:
    hdu 1166 敌军布阵
    UVA 100
    dfs和bfs 变形课
    hdu 1002 A + B Problem II
    连连看 杭电1175
    跳格子 DFS 加 奇偶截枝
    c语言 判断两直线段是否相交
    poj 3067 Japan
    数状数组
    UVA 10881 Piotr's Ants
  • 原文地址:https://www.cnblogs.com/zouhp/p/7188904.html
Copyright © 2011-2022 走看看