zoukankan      html  css  js  c++  java
  • Linq to Object原理

    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;
                    }
                }
            }
        }
    }

  • 相关阅读:
    图形设计 X11
    软件安装 RPM SRPM YUM
    如何将excel表格中的纯数字删掉 空白行,然后删除
    考试机
    程序编译与运行
    基础设定与备份策略
    开机流程 模块管理 Loader
    让所有Excel数据格全部乘 某个数
    转:JDK1.8-Stream()使用详解
    转:IK分词原理
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/10733618.html
Copyright © 2011-2022 走看看