本文共 2544 字,大约阅读时间需要 8 分钟。
using System;using System.Collections;using System.Collections.Generic;/*Lambda 表达式和匿名函数其实是一件事情。不同是,他们语法表现形式不同,Lambda 表达式在语法上实际上就是匿名函数的简写。直接介绍匿名函数和Lambda表达式的用法没什么意思,在这里,我要根据实际应用来讲一个两者用法的例子,这样在介绍知识点的同时也能和大家分享一下解决问题的思想。*/namespace ConsoleApplication18{ public class Product { ////// 商品编号 /// public int ProductID { get; set; } ////// 商品名称 /// public string Name { get; set; } ////// 商品描述 /// public string Description { get; set; } ////// 商品价格 /// public decimal Price { get; set; } ////// 商品分类 /// public string Category { set; get; } } ////// 购物车类 (实现 IEnumerable public class ShoppingCart : IEnumerable接口) /// { public List Products { get; set; } public IEnumerator GetEnumerator() { return Products.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// /// 定义一个静态类,用于实现扩展方法 /// public static class MyExtensionMethods { ////// 商品查询器 /// /// 扩展类型的实例引用 /// 一个参数类型为Product,返回值为bool的委托 ///查询结果 public static IEnumerableFilter(this IEnumerable productEnum, Func selectorParam) { foreach (Product prod in productEnum) { if (selectorParam(prod)) { yield return prod; } } } } class Program { static void Main(string[] args) { // 创建商品集合 IEnumerable products = new ShoppingCart { Products = new List { new Product {Name = "西瓜", Category = "水果", Price = 2.3M}, new Product {Name = "苹果", Category = "水果", Price = 4.9M}, new Product {Name = "ASP.NET MCV 入门", Category = "书籍", Price = 19.5M}, new Product {Name = "ASP.NET MCV 提高", Category = "书籍", Price = 34.9M} } }; //用匿名函数定义一个具体的查询需求 Func fruitFilter = delegate (Product prod) { return prod.Category == "水果"; }; //调用Filter,查询分类为“水果”的商品 IEnumerable filteredProducts = products.Filter(fruitFilter); //打印结果 foreach (Product prod in filteredProducts) { Console.WriteLine("商品名称: {0}, 单价: {1:c}", prod.Name, prod.Price); } Console.ReadKey(); ///=============================== Func fruitFilter1 = prod => prod.Category == "水果"; IEnumerable filteredProducts1 = products.Filter(fruitFilter1); //查询分类为“水果”或者单价大于30元的商品 IEnumerable filteredProducts2 = products.Filter(prod =>prod.Category == "水果" || prod.Price > 30); } }}
转载地址:http://stdaf.baihongyu.com/