From be286cffbdb41d0dc70165b803b4b3a4c2ca67f8 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Mon, 12 Jul 2021 13:28:54 +1000 Subject: [PATCH] e.g. 5.18 Using a Delegate in an Extension Method e.g. 5.19 Using the Filtering Extension Method with a Func --- .../essential_csharp_features/Program.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/chap5_essential_language_features/essential_csharp_features/Program.cs b/chap5_essential_language_features/essential_csharp_features/Program.cs index ee12b6b..78efcba 100644 --- a/chap5_essential_language_features/essential_csharp_features/Program.cs +++ b/chap5_essential_language_features/essential_csharp_features/Program.cs @@ -20,8 +20,15 @@ namespace automatically_implemented_properties new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M} } }; + + Func categoryFilter = delegate(Product prod) + { + return prod.Category == "Soccer"; + }; - foreach (Product prod in products.FilterByCategory("Soccer")) + IEnumerable filteredProducts = products.Filter(categoryFilter); + + foreach (Product prod in filteredProducts) { Console.WriteLine("Name: {0}, Price {1:c}", prod.Name, prod.Price); } @@ -55,5 +62,17 @@ namespace automatically_implemented_properties } } } + + public static IEnumerable Filter(this IEnumerable productEnum, + Func selectorParam) + { + foreach (Product prod in productEnum) + { + if (selectorParam(prod)) + { + yield return prod; + } + } + } } } \ No newline at end of file