三国杀扩展包,c#扩展方法奇思妙用基础篇六:WhereIf 扩展

一、Where 扩展的不足

如下界面,可通过姓名、编号和地址对人员进行模糊查询:
PersonQuery三国杀扩展包,c#扩展方法奇思妙用基础篇六:WhereIf 扩展
我们通常会写出如下代码:

public IQueryable Query(IQueryable source, string name, string code, string address) { var result = source; if(string.IsNullOrEmpty(name) == false) result = source.Where(p => p.Name.Contains(name)); if (string.IsNullOrEmpty(code) == false) result = source.Where(p => p.Code.Contains(code)); if (string.IsNullOrEmpty(address) == false) result = source.Where(p => p.Code.Contains(address)); return result; }
以上代码有大量的 if 显得很繁琐,代码可读性不好。

二、创建并使用 WhereIf 扩展

WhereIf 扩展比较简单,代码如下:
public static IQueryable WhereIf(this IQueryable source, Expression> predicate, bool condition) { return condition ? source.Where(predicate) : source; }
上面的代码可简化成:
public IQueryable Query(IQueryable source, string name, string code, string address) { return source .WhereIf(p => p.Name.Contains(name), string.IsNullOrEmpty(name) == false) .WhereIf(p => p.Code.Contains(code), string.IsNullOrEmpty(code) == false) .WhereIf(p => p.Code.Contains(address), string.IsNullOrEmpty(address) == false); }
是不是更易读一些!
当然,我们还需要一个 IEnumerable 版本的 WhereIf 扩展,方便对集合进行查询:
public static IEnumerable WhereIf(this IEnumerable source, Func predicate, bool condition) { return condition ? source.Where(predicate) : source; }

三、WhereIf 完整代码

namespace System.Linq { public static class WhereIfExtension { public static IQueryable WhereIf(this IQueryable source, Expression> predicate, bool condition) { return condition ? source.Where(predicate) : source; } public static IQueryable WhereIf(this IQueryable source, Expression> predicate, bool condition) { return condition ? source.Where(predicate) : source; } public static IEnumerable WhereIf(this IEnumerable source, Func predicate, bool condition) { return condition ? source.Where(predicate) : source; } public static IEnumerable WhereIf(this IEnumerable source, Func predicate, bool condition) { return condition ? source.Where(predicate) : source; } } }
将类放入 System.Linq 命名空间中,随时使用,更方便。
c#扩展方法奇思妙用》系统文章从 2009 年 08 月开始写起,到现在一共有了 19 篇,欢迎阅读: 基础篇: 中文处理、string 常用扩展、byte 常用扩展、Random 扩展、Dictionary 扩展
高级篇: 改进 Scottgu 的 "In" 扩展、Aggregate扩展其改进、Enumerable.Cast应用、对扩展进行分组管理、ToString(string format) 扩展、WinForm 控件选择器、树”通用遍历器、Type类扩展
变态篇: 由Fibonacci数列引出“委托扩展”及“递推递归委托”、封装 if/else、swith/case及while、switch/case 组扩展、string 的翻身革命
性能篇 扩展方法性能初测
MVC篇: 巧用扩展方法优先级,美化所有页面TextBoxFor文本框
Tags:  显示扩展名 java扩展 扩展卡 扩展名 三国杀扩展包

延伸阅读

最新评论

发表评论