迭代器yield的使用

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

namespace LinqTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>() {30, 58, 62, 40, 20, 10, 43, 12, 45, 134 };
            var list = intList.WhereLinq(s=> {
                Thread.Sleep(200);
                return s < 45;
            });

            foreach(var i in list)
            {
                Console.WriteLine(i);
                if (i < 23)
                    break;
            }
        }
    }

    public static class xxx
    {
        public static IEnumerable<T> WhereLinq<T>(this List<T> lists, Func<T, bool> func)
        {
            foreach (var t in lists)
            {
                if (func.Invoke(t))
                {
                    yield return t;
                }
            }
        }
    }
}

 

posted on 2022-06-15 00:07  itjeff  阅读(32)  评论(0编辑  收藏  举报

导航