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("******************** using an iterator 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; } }
The results can be seen by running time:
Unused iterator wait "WhereNoYield" function after the completion of the operation, then the print data
When using an iterator, each execution "WhereWithYield" function will directly print data