using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace ConsoleAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<Student>()
            {
                new Student(){ Age=1,Name="A1",Money=1.1m},
                new Student(){ Age=2,Name="A2",Money=1.1m},
                new Student(){ Age=3,Name="A3",Money=1.1m},
                new Student(){ Age=4,Name="A4",Money=1.1m},
                new Student(){ Age=5,Name="A5",Money=1.1m},
                new Student(){ Age=6,Name="A6",Money=1.1m},
            };
            list.Select(x => new { x.Age, x.Money });
            var nlist = list.MyWhere(x =>
            {
                Thread.Sleep(100 * x.Age);
                Console.WriteLine(x.Age);
                return x.Age > 3;
            });
            Console.WriteLine("我还没foreach");
            foreach (var item in nlist)
            {
                Console.WriteLine($"{item.Name}:{item.Age}");
            }
            Console.ReadLine();
        }
    }

    public class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public decimal Money { get; set; }
    }

    public static class MyLinq
    {
        /// <summary>
        /// 1 通过委托封装 做到了代码的复用
        /// 2 泛型 符合任意类型的数据筛选
        /// 3 静态扩展 方便调用
        /// 4 按需筛选 延迟加载 基于yield实现(语法糖,状态机)
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static IEnumerable<TSource> MyWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
        {
            foreach (var item in source)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }
    }
}

 Linq to Object原理 随笔

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄