首页 > 其他 > 详细

yield迭代器的使用

时间:2019-08-25 10:37:02      阅读:87      评论:0      收藏:0      [点我收藏+]
class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            for (int i = 0; i < 10; i++)
            {
                students.Add(new Student() { Age = i, Name = "名字" + i });
            }

            {
                Console.WriteLine("********************未使用迭代器 Start*****************************");
                List<Student> query = students.WhereNoYield(s =>
                {
                    Thread.Sleep(300);
                    return s.Age > 0;
                });
                foreach (var item in query)
                {
                    Console.WriteLine($"{DateTime.Now} - {item.Age} - {item.Name}");
                }
                Console.WriteLine("********************未使用迭代器 End*****************************");
            }


            {
                Console.WriteLine("********************使用迭代器 Start*****************************");
                IEnumerable<Student> query = students.WhereWithYield(s =>
                {
                    Thread.Sleep(300);
                    return s.Age > 0;
                });
                foreach (var item in query)
                {
                    Console.WriteLine($"{DateTime.Now} - {item.Age} - {item.Name}");
                }
                Console.WriteLine("********************使用迭代器 End*****************************");
            }

            Console.ReadKey();
        }
    }

    public static class MyClass
    {
        public static IEnumerable<T> WhereWithYield<T>(this IEnumerable<T> list, Func<T, bool> func)
        {
            foreach (var item in list)
            {
                if (func.Invoke(item))
                {
                    yield return item;
                }
            }
        }

        public static List<T> WhereNoYield<T>(this List<T> list, Func<T, bool> func)
        {
            List<T> lists = new List<T>();
            foreach (var item in list)
            {
                if (func.Invoke(item))
                {
                    lists.Add(item);
                }
            }
            return lists;
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

通过运行结果时间可以看出:

未使用迭代器,等待“WhereNoYield”函数运算完成后,再进行打印数据

使用迭代器,每次执行“WhereWithYield“函数时,会直接打印数据

技术分享图片

yield迭代器的使用

原文:https://www.cnblogs.com/lishuyi/p/11406761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!