首页 > 其他分享 >.Net 使用扩展方法将Where扩展成WhereIf

.Net 使用扩展方法将Where扩展成WhereIf

时间:2023-03-05 23:23:44浏览次数:37  
标签:predicate WhereIf 扩展 list Add query Net condition

  官方的Linq中并没有WhereIf方法,为了方便我们的日常开发,使用扩展方法实现WhereIf。

public static class QueryableExtensions
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
    {
        return condition ? query.Where(predicate) : query;
    }

    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, int, bool>> predicate)
    {
        return condition ? query.Where(predicate) : query;
    }

    public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> query, bool condition, Func<T, bool> predicate)
    {
        return condition ? query.Where(predicate) : query;
    }
}

  扩展后就能直接使用WhereIf

List<int> list = new List<int>();

list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
list.Add(9);

bool flag = true;

list = list.WhereIf(flag, a => a >= 5).ToList();

标签:predicate,WhereIf,扩展,list,Add,query,Net,condition
From: https://www.cnblogs.com/weidaorisun/p/17182158.html

相关文章

  • php 安装 swoole 扩展
    swoole下载地址:​​http://www.swoole.com/​​安装教程://解压tar-zxvfswoole-src-1.9.0-stable.tar.gzcdswoole-src-1.9.0-stable/usr/local/php/bin/phpize./confi......
  • Asp.net core mapcontrollers 背后干了些啥
    1.背景当我们在写webapi的时候我们发现,框架自动帮我们写好了app.MapControllers(),看注释写的是帮我们将controllerl里面的action映射为我们的终结点,那具体是怎么弄得呢,......
  • .net6 引用log4net记录日志
    第一步:nuget包引用使用log4net需要引用两个nuget包1.Log4net2.Microsoft.Extensions.Logging.Log4Net.AspNetCore第二步:引用log4net的config配置文件配置文件贴......
  • 如何编写Kubernetes的YAML(一)
    什么是API对象作为一个集群操作系统,Kubernetes归纳总结了Google多年的经验,在理论层面抽象出了很多个概念,用来描述系统的管理运维工作,这些概念就叫做“API对象”。因......
  • DotNet 5.0 部署 Docker 注意
    1.添加docker环境参数后会报错      日志显示  只好按照以下注释   2.Dockerfile问题  日志记载        日志显示......
  • C#/.net面试知识点总结【反射】(二)
    反射?通过反射调用对象要比直接NEW一个对象慢多 https://www.jb51.net/article/205935.htm动态获取程序集信息。程序集包含模块,而模块又包括类型,类型下有成员,反射就是管理......
  • Kubernetes(k8s)权限管理RBAC详解
    一、简介kubernetes集群相关所有的交互都通过apiserver来完成,对于这样集中式管理的系统来说,权限管理尤其重要,在1.5版的时候引入了RBAC(RoleBaseAccessControl)的权限......
  • C#/.net面试知识点总结(六)【垃圾回收器】
    托管代码可是享受CLR提供的服务(安全检测,垃圾回收,)不需要自己完成这些操作非托管代码需要自己提供安全检测,垃圾回收等操作 托管代码是一种中间语言,运行在CLR上。非托管代......
  • C#/.net 序列化与反序列化
    序列化就是将我们程序中的对象通过字节流写入存储媒体或网络流中。反序列化就是把已存入的媒体或接收的网络流中的内容转换成程序运行中的对象。这两个过程结合起来,可以轻......
  • .NET6 MVC 传值的五种方式
    //Controller:ViewBag.User1="张三";ViewData["User2"]="李四";TempData["User3"]="王五";HttpContext.Sessio......