yield迭代器的使用

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“函数时,会直接打印数据

猜你喜欢

转载自www.cnblogs.com/lishuyi/p/11406761.html