不用讲原理,直接上代码
你知道其实LINQ TO OBJECTS和LINQ TO XXX都可以自己实现么?
我们先实现一个L2O,注意,我们注释掉using System.Linq;并且自己写两个方法Where和Select
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var query = from x in new int[] { 1, 2, 3, 4, 5 }
where x > 3
select x.ToString();
foreach (var item in query)
Console.WriteLine(item);
}
}
static class MyLinq
{
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> data, Func<TSource, TResult> selector)
{
Console.WriteLine("select");
foreach (TSource item in data)
yield return selector(item);
}
public static IEnumerable<T> Where<T>(this IEnumerable<T> data, Func<T, bool> predicate)
{
Console.WriteLine("where");
foreach (T item in data)
if (predicate(item)) yield return item;
}
}
}
运行
select
where
4
5
Press any key to continue . . .