1 class Program 2 { 3 static void Main(string[] args) 4 { 5 string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; 6 7 //使用yield ruturn的解决方案。 8 var namesFive = GetFiveName(names); 9 10 foreach (var n in namesFive) 11 { 12 Console.WriteLine(n); 13 } 14 15 16 foreach (string item in namesFive) 17 { 18 Console.WriteLine(item); 19 } 20 21 } 22 23 //老式的做法 24 //private static IEnumerable GetFiveName(string[] ts) 25 //{ 26 // List<string> fiveNames = new List<string>(); 27 // foreach (var item in ts) 28 // { 29 // if (item.Length == 5) 30 // { 31 // fiveNames.Add(item); 32 // //yield return item; 33 // } 34 // } 35 // return fiveNames; 36 //} 37 38 private static IEnumerable GetFiveName(string[] ts) 39 { 40 foreach (var item in ts) 41 { 42 if (item.Length == 5) 43 { 44 yield return item; 45 } 46 } 47 } 48 }
原文地址:https://www.cnblogs.com/myBlogOu/p/9939602.html
时间: 2024-10-30 04:13:25