Lambda入门示例实例
一些lambda的基础知识,例子都非常的简单.
class Program { delegate int 乘法(int i); static void Main(string[] args) { //显示数组中大于5的(); //找出字符串中包含o的字符串(); //显示年龄大于20岁的人且计数(); //用枚举器显示年龄大于20岁的(); //委托乘法(); //显示字符串以J开头的(); //整数数组排序(); //按年龄大小排序(); //取出姓的唯一值并打印出详细清单(); Console.ReadLine(); } private static void 显示年龄大于20岁的人且计数() { var names = new[]{ new {Name="jack",Age=20}, new {Name="rose",Age=10}, new {Name="tom",Age=30}, new {Name="jerry",Age=40}, new {Name="Black",Age=50}, }; var output = names.Where(p => p.Age > 20); foreach (var item in output) { Console.WriteLine("名字是{0},年龄是{1}", item.Name, item.Age); } Console.WriteLine("年龄大于20岁的一共有:{0}", output.Count()); } private static void 取出姓的唯一值并打印出详细清单() { var names = new[]{ new {Name="jack 盖茨",Age=20}, new {Name="rose 吴",Age=10}, new {Name="tom 邓",Age=30}, new {Name="jerry 盖茨",Age=40}, new {Name="Black 吴",Age=50}, }; var output = names.GroupBy(p => p.Name.Split(' ')[1]); foreach (var item in output) { Console.WriteLine(item.Key); foreach (var 详细 in item) { Console.WriteLine(" " + 详细); } } } private static void 按年龄大小排序() { var names = new[]{ new {Name="jack",Age=20}, new {Name="rose",Age=10}, new {Name="tom",Age=30}, new {Name="jerry",Age=40}, new {Name="Black",Age=50}, }; var output = names.OrderBy(p => p.Age).Select(p => p); foreach (var item in output) { Console.WriteLine("名字是{0},年龄是{1}", item.Name, item.Age); } } private static void 整数数组排序() { int[] arr = { 5, 8, 9, 1, 4, 2, 3 }; var output = arr.OrderBy(p => p); foreach (var item in output) { Console.WriteLine(item); } } private static void 显示字符串以J开头的() { string[] str = { "tom", "jerry", "jack", "rose" }; var output = str.Select(p => p).Where(p => p.StartsWith("j")); foreach (var item in output) { Console.WriteLine(item); } } private static void 委托乘法() { 乘法 x2; x2 = p => p * 2; for (int i = 0; i < 10; i++) { Console.WriteLine(x2(i)); } x2 = p => p * p; for (int i = 0; i < 10; i++) { Console.WriteLine(x2(i)); } } private static void 用枚举器显示年龄大于20岁的() { var names = new[]{ new {Name="jack",Age=20}, new {Name="rose",Age=10}, new {Name="tom",Age=30}, new {Name="jerry",Age=40}, new {Name="Black",Age=50}, }; var ie = names.Where(p => p.Age > 20).Select(p => p); var output = ie.GetEnumerator(); while (output.MoveNext()) { Console.WriteLine("名字是{0},年龄是{1}", output.Current.Name, output.Current.Age); } } private static void 找出字符串中包含o的字符串() { string[] str = { "tom", "jerry", "jack", "rose" }; var output = str.Select(p => p).Where(p => p.ToCharArray().Contains('o')); foreach (var item in output) { Console.WriteLine(item); } } private static void 显示数组中大于5的() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var output = arr.Select(p => p).Where(p => p > 5); foreach (var item in output) { Console.WriteLine(item); } } }