From e2aa8c7cba667df2e43a99e3e3d68316721fcb91 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Thu, 15 Jul 2021 16:56:14 +1000 Subject: [PATCH] e.g. 5.26 Querying Without LINQ --- .../essential_csharp_features/Program.cs | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/chap5_essential_language_features/essential_csharp_features/Program.cs b/chap5_essential_language_features/essential_csharp_features/Program.cs index ac6522a..aa82ade 100644 --- a/chap5_essential_language_features/essential_csharp_features/Program.cs +++ b/chap5_essential_language_features/essential_csharp_features/Program.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using automatically_implemented_properties; namespace automatically_implemented_properties @@ -9,29 +10,31 @@ namespace automatically_implemented_properties { static void Main(string[] args) { - // create and populate Shopping Cart, implementing IEnumerable interface - IEnumerable products = new ShoppingCart + Product[] products = { - Products = new List - { - 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.50M}, - new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M} - } + 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.50M}, + new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M} }; - IEnumerable filteredProducts = products.Filter(prod => - prod.Category == "Soccer" || - prod.Price > 20); - - foreach (Product prod in filteredProducts) + // define the array to hold results + Product[] results = new Product[3]; + // sort the contents of the array + Array.Sort(products, (item1, item2) => { - Console.WriteLine("Name: {0}, Price {1:c}", prod.Name, prod.Price); + return Comparer.Default.Compare(item1.Price, item2.Price); + }); + // get the first three items in the array as the results + Array.Copy(products, results, 3); + // print out the name + foreach (Product p in results) + { + Console.WriteLine("Item: {0}, Cost: {1}", p.Name, p.Price); } - decimal total = products.FilterByCategory("Soccer").TotalPrices(); - Console.WriteLine("Filtered total: {0:c}", total); + int count = 0; + // print the name } }