CSharp的Where底层实现

发布时间 2023-07-03 20:54:40作者: 流浪のwolf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

// 命名空间
namespace pro01
{
    //
    internal class Program
    {
        // main 方法
        static async Task Main(string[] args)
        {
            // 定义一个整形的数组
            int[] nums = new int[] { 2, 3, 4, 6, 12, 4 ,13};
            // 取出大于 10 的数
            // ps:Where 是数组的扩展的方法 需要 using 引入
            IEnumerable<int> result = nums.Where(a => a > 10);  // a 是每一项  返回满足条件的所有项【集合】
            foreach (int i in result)
            {
                Console.WriteLine(i);
            }

            // 自己写一个 where 方法
            IEnumerable<int> result1 = MyWhere(nums,a => a > 12);  // a 是每一项  返回满足条件的所有项【集合】
            foreach (int i in result1)
            {
                Console.WriteLine(i);
            }


            Console.ReadLine();
        }
        static IEnumerable<int> MyWhere(IEnumerable<int> items, Func<int, bool> f)
        {
            List<int> result = new List<int>();
            foreach (var i in items )
            {
                // 满足条件的加入 result 集合
                if (f(i) == true) result.Add(i);
            }
            return result;
        }
    }
}