对IEnumerable<T>执行标准并且同样返回IEnumerable<T>的扩展方法,可以使用yield关键字对源数据中的项应用选择标准,已生成精简的结果集。
public static IEnumerable<Product> FilterByCategory(this IEnumerable<Product>productEnum,string categoryParam) { foreach (Product prod in productEnum) { if (prod.Category == categoryParam) { yield return prod; } } }
使用
protected string GetMessage() { IEnumerable<Product> products = new ShoppingCart { Products = new List<Product> { new Product {Name ="Kayak",Category="Watersports",Price=275M}, new Product {Name ="Lifejacket",Category="Watersports",Price=48.95M}, new Product {Name ="Soccer ball",Category="Soccer",Price=19.5M}, new Product {Name ="Corner flag",Category="Soccer",Price=34.95M} } }; decimal total = products.FilterByCategory("Soccer").TotalPrices(); return String.Format("Soccer Total:{0:c}", total); }