LINQ方法实际上是对IEnumerable<TSource>的扩展,如图:

 

本篇自定义一个MyWhere方法,达到与Where相同的效果。

 

  使用LINQ自带的Where方法

    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>(){1, 2, 3};
            IEnumerable<int> query = list.Where(x => x%2 == 0);
            list.Add(4);
            showConsole(query);
            Console.ReadKey();
        }
 
        private static void showConsole<T>(IEnumerable<T> list)
        {
            foreach (T item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

结果:

 

这样的结果符合LINQ的"延迟加载"的特点,虽然是在IEnumerable<int> query = list.Where(x => x%2 == 0)之后为集合添加元素list.Add(4),但直到调用showConsole(query)遍历,查询才真正执行。

 

  自定义一个MyWhere,无延迟加载

□ 首先想到的是对IEnumerable<TSource>的扩展,创建静态方法和静态类。

 public static class Extension
    {
        //Func<TSource, bool>是委托,返回的是bool类型 
        public static IEnumerable<TSource> MyWhere<TSource>(this IEnumerable<TSource> source,
            Func<TSource, bool> predicate)
        {
            if(source==null) throw new ArgumentException();
            if(predicate==null) throw new ArgumentException();
            List<TSource> result = new List<TSource>();
            foreach (TSource item in source)
            {
                if (predicate(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

□ 执行主程序

    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>(){1, 2, 3};
            IEnumerable<int> query = list.MyWhere(x => x % 2 == 0);
            list.Add(4);
            showConsole(query);
            Console.ReadKey();
        }
 
        private static void showConsole<T>(IEnumerable<T> list)
        {
            foreach (T item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 结果  

 

这样的结果丢掉了LINQ的"延迟加载"的特点,也就是后加元素list.Add(4)之后,没有再对集合进行遍历。

可希望的结果是:

● 后加元素list.Add(4)之后,还需要遍历集合

● 返回结果还是IEnumerable<TSource>类型

 

于是,想到了Decorator设计模式,使用它能满足以上2个条件。

 

  自定义一个MyWhere,也有延迟加载,使用Decorator设计模式

 

● 为了返回IEnumerable<TSource>类型,必须让装饰者类实现IEnumerable<T>接口

● 装饰者类最重要的特点是包含目标参数类型的引用

● 为了能遍历,装饰者类内部还包含了一个迭代器

 

   public class WhereDecorator<T> : IEnumerable<T>
    {
        private IEnumerable<T> list;
        private Func<T, bool> predicate;
 
        public WhereDecorator(IEnumerable<T> list, Func<T, bool> predicate)
        {
            this.list = list;
            this.predicate = predicate;
        }
 
        public IEnumerator<T> GetEnumerator()
        {
            return new WhereEnumerator<T>(list, predicate);
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return new WhereEnumerator<T>(list, predicate);
        }
 
        public class WhereEnumerator<T> : IEnumerator<T>
        {
            private List<T> innerList;
            private int index;
 
            public WhereEnumerator(IEnumerable<T> list, Func<T, bool> predicate)
            {
                innerList = new List<T>();
                index = -1;
                foreach (T item in list)
                {
                    if (predicate(item))
                    {
                        innerList.Add(item);
                    }
                }
            }
 
            public T Current
            {
                get { return innerList[index]; }
            }
 
            public void Dispose()
            {
                
            }
 
            object System.Collections.IEnumerator.Current
            {
                get { return innerList[index]; }
            }
 
            public bool MoveNext()
            {
                index++;
                if (index >= innerList.Count)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
 
            public void Reset()
            {
                index = -1;
            }
        }
    }
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

自定义MyWhere中,现在可以使用装饰者类来返回一个实例。

    public static class Extension
    {
        public static IEnumerable<TSource> MyWhere<TSource>(this IEnumerable<TSource> source,
            Func<TSource, bool> predicate)
        {
            if(source==null) throw new ArgumentException();
            if(predicate==null) throw new ArgumentException();
            return new WhereDecorator<TSource>(source, predicate);
        }
    }    

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

主程序中:

    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>(){1, 2, 3};
            IEnumerable<int> query = list.MyWhere(x => x % 2 == 0);
            list.Add(4);
            showConsole(query);
            Console.ReadKey();
        }
 
        private static void showConsole<T>(IEnumerable<T> list)
        {
            foreach (T item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

结果:

可见,与LINQ的Where方法返回结果一样。

 

  总结

 

● 所有的LINQ方法是对IEnumerable<T>的扩展

● 当我们想对方法返回的结果再进行链式操作的时候,装饰者类就包含方法参数类型的引用并返回与该方法相同的类型。

● 这里的装饰者类需要完成遍历,装饰者类必须实现IEnumerable<T>,内部必须存在迭代器实现IEnumerator<T>接口。

21扩展IEnumerable<T>泛型接口自定义LINQ的扩展方法的更多相关文章

  1. .NET中扩展方法和Enumerable(System.Linq)

    LINQ是我最喜欢的功能之一,程序中到处是data.Where(x=x>5).Select(x)等等的代码,她使代码看起来更好,更容易编写,使用起来也超级方便,foreach使循环更加容易,而不 ...

  2. C# IEnumerable与IQueryable ,IEnumerable与IList ,LINQ理解Var和IEnumerable

    原文:https://www.cnblogs.com/WinHEC/articles/understanding-var-and-ienumerable-with-linq.html 使用LINQ从数 ...

  3. IEnumerable和IQueryable和Linq的查询

    IEnumerable和IEnumerable 1.IEnumerable查询必须在本地执行.并且执行查询前我们必须把所有的数据加载到本地.而且更多的时候.加载的数据有大量的数据是我们不需要的无效数据 ...

  4. atitit. 集合groupby 的实现(2)---自定义linq查询--java .net php

    atitit.  集合groupby 的实现(2)---自定义linq查询--java .net php 实现方式有如下 1. Linq的实现原理流程(ati总结) 1 2. groupby  与 事 ...

  5. Linq的Distinct方法的扩展

    原文地址:如何很好的使用Linq的Distinct方法 Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1&qu ...

  6. ReactiveX 学习笔记(11)对 LINQ 的扩展

    Interactive Extensions(Ix) 本文的主题为对 Ix 库,对 LINQ 的扩展. Buffer Ix.NET Buffer Ix.NET BufferTest Buffer 方法 ...

  7. NHibernate Linq查询 扩展增强 (第九篇)

    在上一篇的Linq to NHibernate的介绍当中,全部是namespace NHibernate命名空间中的IQueryOver<TRoot, TSubType>接口提供的.IQu ...

  8. 【C#夯实】我与接口二三事:IEnumerable、IQueryable 与 LINQ

    序 学生时期,有过小组作业,当时分工一人做那么两三个页面,然而在前端差不多的时候,我和另一个同学发生了争执.当时用的是简单的三层架构(DLL.BLL.UI),我个人觉得各写各的吧,到时候合并,而他觉得 ...

  9. 记录一次源码扩展案列——FastJson自定义反序列化ValueMutator

    背景:曾经遇到一个很麻烦的事情,就是一个json串中有很多占位符,需要替换成特定文案.如果将json转换成对象后,在一个一个属性去转换的话就出出现很多冗余代码,不美观也不是很实用. 而且也不能提前在j ...

随机推荐

  1. 最简单删除SQL Server中所有数据的方法(不用考虑表之间的约束条件,即主表与子表的关系)

    其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间可能形成相互约束关系,删除操作可能陷入死循环,二是这里使用了微软未正式公开的sp_MSF ...

  2. 我常用的 Python 调试工具 - 博客 - 伯乐在线

    .ckrating_highly_rated {background-color:#FFFFCC !important;} .ckrating_poorly_rated {opacity:0.6;fi ...

  3. C#socket编程序(一)

    在讲socket编程之前,我们先看一下最常用的一些类和方法,相信这些能让你事半功倍. 一.IP地址操作类 1.IPaddress类 a.在该类中有一个 parse()方法,能够把点分十进制IP地址 转 ...

  4. scrapy-redis 更改队列和分布式爬虫

    这里分享两个技巧 1.scrapy-redis分布式爬虫 我们知道scrapy-redis的工作原理,就是把原来scrapy自带的queue队列用redis数据库替换,队列都在redis数据库里面了, ...

  5. Just a Hook (线段树)

    给你n个数(初始时每个数的值为1),m个操作,每个操作把区间[l,r]里的数更新为c,问最后这n个数的和是多少. 区域更新用懒惰标记 #include<bits/stdc++.h> usi ...

  6. Bubbo的启动时检查

    这个地方参考dubbo的官网,不是很难,为了使得文档的完整,也单独起一章. 1.默认 Dubbo 缺省会在启动时检查依赖的服务是否可用,不可用时会抛出异常,阻止 Spring 初始化完成,以便上线时, ...

  7. Session机制三(表单的重复提交)

    1.表单的重复提交的情况 在表单提交到一个servlet,而servlet又通过请求转发的方式响应了一个JSP页面,这个时候地址栏还保留这servlet的那个路径,在响应页面点击刷新. 在响应页面没有 ...

  8. 使用chrales抓包IOS的https(pc+手机)

    1.安装SSL证书到手机 点击 Help -> SSL Proxying -> Install Charles Root Certificate on a Mobile Device 2. ...

  9. Collabtive 系统 SQL 注入实验(补充)

    SQL Injection:就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令. 具体来说,它是利用现有应用程序,将(恶意)的SQL命令注 ...

  10. 基于五阶段流水线的RISC-V CPU模拟器实现

    RISC-V是源自Berkeley的开源体系结构和指令集标准.这个模拟器实现的是RISC-V Specification 2.2中所规定RV64I指令集,基于标准的五阶段流水线,并且实现了分支预测模块 ...