一、Where 扩展的不足
如下界面,可通过姓名、编号和地址对人员进行模糊查询:我们通常会写出如下代码:
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
上面的代码可简化成:
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
public static IEnumerable
三、WhereIf 完整代码
namespace System.Linq { public static class WhereIfExtension { public static IQueryable将类放入 System.Linq 命名空间中,随时使用,更方便。
《c#扩展方法奇思妙用》系统文章从 2009 年 08 月开始写起,到现在一共有了 19 篇,欢迎阅读: 基础篇: 中文处理、string 常用扩展、byte 常用扩展、Random 扩展、Dictionary
高级篇: 改进 Scottgu 的 "In" 扩展、Aggregate扩展其改进、Enumerable.Cast
变态篇: 由Fibonacci数列引出“委托扩展”及“递推递归委托”、封装 if/else、swith/case及while、switch/case 组扩展、string 的翻身革命
性能篇: 扩展方法性能初测
MVC篇: 巧用扩展方法优先级,美化所有页面TextBoxFor文本框
最新评论