最近在做一个webAPI 的时候遇到一个需要合并多个predicate条件的问题,下面就是对题的情况。为了方便交流我对case进行了简化,请先看如下代码:

using System.Collections.Generic;
using System.Linq; namespace CombineLinqPredicates
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
} class Program
{
static void Main(string[] args)
{
var customers = GetCustomers(); var filterCustomers = customers.Where(x => x.Id == );
} private static IEnumerable<Customer> GetCustomers()
{
return new List<Customer>()
{
new Customer(){Id=,Name="Alibaba",Url= "http://www.taobao.com"},
new Customer(){Id=,Name="Jd",Url= "http://www.jd.com"},
new Customer(){Id=,Name="Tencent",Url= "http://www.qq.com"}
};
}
}
}

代码非常简单,一个customer 对象有三个属性,id, name 和 url.  和一个过去customer list的方法 GetCustomers.

在Main方法中, 我通过

var filterCustomers = customers.Where(x => x.Id == 2); 

获取了所有id = 2 的customer 对象。

假如现在 where 条件中的 ID 需要从 UI 获取,而且我需要再添加一个 条件,比如url 中包含 jd 字符串如何做呢?

代码可能变成:

            int? inputCustomerId = null;
string inputUrl = null;
var customers = GetCustomers();
//从UI获取值并填充到 inputCustomerId,inputUrl, 这个过程我们省略。
var filterCustomers = customers;
if (inputCustomerId.HasValue) filterCustomers = filterCustomers.Where(x => x.Id == inputCustomerId.Value);
if (!string.IsNullOrEmpty(inputUrl)) filterCustomers = filterCustomers.Where(x => x.Url.Contains(inputUrl));

在上面的代码中有两次过滤,为了避免这个问题,提高性能,我们需要合并这两个where 条件。

首先我们看下where 条件的定义:

 public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

  他的参数类型是 Func<TSource, bool>型的,因此我么可以定义一个类型如下,然后进行合并,具体代码如下:

            Func<Customer, bool> idFilter = x => inputCustomerId.HasValue && x.Id == inputCustomerId.Value;
Func<Customer, bool> urlFilter = x => !string.IsNullOrEmpty(inputUrl) && x.Url.Contains(inputUrl);
Func<Customer, bool> filter = x => true && idFilter(x) && urlFilter(x); filterCustomers = customers.Where(filter);

这样处理后,就解决了二次过滤的问题。

linq中如何合并多个predicate条件的更多相关文章

  1. 2.4 LINQ中使用where子句指定筛选条件

    本篇讲解的内容有: 使用where筛选过滤LINQ查询 带逻辑的where筛选 多个where筛选子句 [1.使用where筛选过滤LINQ查询] 通常一个LINQ查询不会如前面的示例代码这么简单,经 ...

  2. LinQ中合并、连接、相交、与非查询

    LinQ中Union合并查询:连接不同的集合,自动过滤相同项:延迟.即是将两个集合进行合并操作,过滤相同的项 var cities = (from p in mylinq.System_Places ...

  3. Rafy 中的 Linq 查询支持(根据聚合子条件查询聚合父)

    为了提高开发者的易用性,Rafy 领域实体框架在很早开始就已经支持使用 Linq 语法来查询实体了.但是只支持了一些简单的.常用的条件查询,支持的力度很有限.特别是遇到对聚合对象的查询时,就不能再使用 ...

  4. linq中的contains条件

    linq中的contains条件   在sql查询语句中,in 在linq 中用contains,并且contains前面是数组,而后面是列名,如: SELECT distinct BH FROM c ...

  5. linq中如何实现多个条件的联合查询

    目前接触处理数据这一块比较多,在处理内存中的数据源的时候我一般使用的是linq,linq使用起来像sql语句一样,用法简单,功能强大. 最近需要实现一个从两个不同的文件读取不同的数据,然后根据这两个数 ...

  6. Linq中关键字的作用及用法

    Linq中关键字的作用及用法 1.All:确定序列中的所有元素是否都满足条件.如果源序列中的每个元素都通过指定谓词中的测试,或者序列为空,则为 true:否则为 false. Demo: 此示例使用 ...

  7. 转载Linq中GroupBy方法的使用总结

    Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等. Linq中的Groupby方法也有这种功能.具体实现看代码: 假设有如下的一个数据集: public class St ...

  8. Linq中join & group join & left join 的用法

    Linq中join & group join & left join 的用法 2013-01-30 11:12 12154人阅读 评论(0) 收藏 举报  分类: C#(14)  文章 ...

  9. 简述Linq中.ToList(), .AsEnumerable(), AsQueryable()的区别和用法

    [TOC] 这3个方法的功能完全不同, 应按照具体业务场景使用. AsQueryable() 先说说什么是 IQueryable IQueryable 是当前的 data provider 返回的类型 ...

随机推荐

  1. Android 模糊搜索rawquery bind or column index out of range: handle 0x2fb180 报错

    做模糊搜索时,出现了  bind or column index out of range: handle 0x2fb180 报错 public Cursor getTitle(String word ...

  2. ubuntu下共享wifi 使用kde5-nm-connection-editor

    1.首先按照正常的建立方法把wifi建立好,然后在软件中心搜索 network ,点击安装 kde5-nm-connection-editor. 2.在终端里输入kde5-nm-connection- ...

  3. Network基础(二):数制转换

    一.数制转换 目标: 1)请将下列数字转换为十进制数: (110010011111)2 .(10110101110)2 2)请将下列十进制数转换为二进制: 156.2608.1043 方案: 使用按权 ...

  4. mysql添加索引和sql分析

    mysql索引操作 查看索引 show indexes from students; #students为表名 mysql添加索引命令 创建索引 .PRIMARY KEY(主键索引) mysql> ...

  5. flutter环境搭建及跑起来demo(多图慎入)

    话不多说,直接上 [1]环境搭建 从git上面clone下来 git clone -b beta https://github.com/flutter/flutter.git 由于国内网络的问题,我就 ...

  6. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】01、环境准备

    开发环境 windows+STS(一个针对Spring优化的Eclipse版本)+Maven+SQLServer 环境部署 1.安装SQLServer(使用版本2008R2) 自行安装,此处略过 2. ...

  7. 46、tensorflow入门初步,手写识别0,1,2,3,4,5,6

    1.使用tensorflow的SoftMax函数,对手写数字进行识别 Administrator@SuperComputer MINGW64 ~ $ docker run -it -p 8888:88 ...

  8. mybatis plus CRUD

    首先我们的项目建立之后我们要建立一个实体类来对应我们的数据裤中的信息 employee import com.baomidou.mybatisplus.annotation.IdType; impor ...

  9. how to convert from hex to disasm

    cat ascii.hex | ascii2binary -b h -t us > ascii.bin x86dis -e 0 -s att -f ascii.bin echo "d8 ...

  10. 慎用margin系列1---CSS的margin塌陷(collapse) 问题与对策

      对于以下简单代码: 如果您认为应该是这样的话: 那就错了.结果是这样的: 因为CSS中存在一个margin collapse,即边界塌陷或者说边界重叠.对于上下两个并列的div块而言,上面div的 ...