using System; using System.Collections.Generic; namespace YieldReturn { class Program { static void Main(string[] args) { var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var resultNormal = EvenNormal(list); foreach (var item in resultNormal) { Console.WriteLine(item); } var resultYieldReturn = EvenYieldReturn(list); foreach (var item in resultYieldReturn) { Console.WriteLine(item); } } static IEnumerable<int> EvenNormal(List<int> list) { var result = new List<int>(); foreach (var item in list) { if (item % 2 == 0) { result.Add(item);// 类似DataSet(整个结果集加载到内存中),适合少量数据的遍历 } } return result; } static IEnumerable<int> EvenYieldReturn(List<int> list) { foreach (var item in list) { if (item % 2 == 0) { yield return item;// 类似DataReader(读取一条返回一条),适合海量数据的遍历 } } yield break; } } }
原文:https://www.cnblogs.com/xiaowangzhi/p/9446572.html