Linq to Object原理

时间:2023-03-09 16:43:47
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=,Name="A1",Money=1.1m},
new Student(){ Age=,Name="A2",Money=1.1m},
new Student(){ Age=,Name="A3",Money=1.1m},
new Student(){ Age=,Name="A4",Money=1.1m},
new Student(){ Age=,Name="A5",Money=1.1m},
new Student(){ Age=,Name="A6",Money=1.1m},
};
list.Select(x => new { x.Age, x.Money });
var nlist = list.MyWhere(x =>
{
Thread.Sleep( * x.Age);
Console.WriteLine(x.Age);
return x.Age > ;
});
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原理