zoukankan      html  css  js  c++  java
  • Lamda表达式Expression<Func<T, bool>>与Func<T, bool>

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

    Expression<Func<TObject, bool>>是表达式,编译后就会变成delegate,才能运行。

    举例:

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

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

    然后你就可以调用func:

    func(5) //-返回 true

    func(200) //- 返回 false

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

    =====================================

    错误的代码:

    //错误的代码

    Func<QuestionFeed, bool> predicate = null;
    if (type == 1)
    {
        predicate = f => f.FeedID == id && f.IsActive == true;
    }
    else
    {
        predicate = f => f.FeedID == id;
    }
    //_questionFeedRepository.Entities的类型为IQueryable<QuestionFeed>
    _questionFeedRepository.Entities.Where(predicate);

    上面代码逻辑是根据条件动态生成LINQ查询条件,将Func类型的变量作为参数传给Where方法。

    实际上Where要求的参数类型是:Expression<Func<TSource, bool>>。

    正确的代码:
    //正确的代码
    Expression<Func<QuestionFeed, bool>> predicate=null;
    if (type == 1)
    {
        predicate = f => f.FeedID == id && f.IsActive == true;
    }
    else
    {
        predicate = f => f.FeedID == id;
    }
    _questionFeedRepository.Entities.Where(predicate);
     
    用委托来执行:
    把所有的数据从Db中取出后(集合)再给委托来筛选。
    用表过式执行时:
    把表达式译成SQL语句执行(由EF完成)。
     
  • 相关阅读:
    健康检查详解:机制、配置、对比、实操
    制作自签名证书
    常用的UML建模
    UML建模更好的表达产品逻辑
    常用的UML建模
    UML建模图实战笔记
    领域驱动设计学习之路—DDD的原则与实践
    DDD领域驱动设计理论篇
    WAN、LAN、WLAN三种网口的区别
    新生代Eden与两个Survivor区的解释
  • 原文地址:https://www.cnblogs.com/wfy680/p/15488234.html
Copyright © 2011-2022 走看看