5.1.5 Creating Filtering Extension Methods

chap5
Jason Zhu 2021-07-12 12:15:56 +10:00
parent ec983ff21c
commit 61cf1cbfaf
1 changed files with 23 additions and 19 deletions

View File

@ -14,28 +14,20 @@ namespace automatically_implemented_properties
{
Products = new List<Product>
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", 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}
}
};
// create and populate an array of Product objects, implementing IEnumerable<Product> interface
Product[] productArray =
foreach (Product prod in products.FilterByCategory("Soccer"))
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
};
Console.WriteLine("Name: {0}, Price {1:c}", prod.Name, prod.Price);
}
// get total value of the products in cart
decimal cartTotal = products.TotalPrices();
decimal arrayTotal = productArray.TotalPrices();
Console.WriteLine("Total: {0:c}", cartTotal);
Console.WriteLine("Array Total: {0:c}", arrayTotal);
decimal total = products.FilterByCategory("Soccer").TotalPrices();
Console.WriteLine("Filtered total: {0:c}", total);
}
}
@ -51,5 +43,17 @@ namespace automatically_implemented_properties
}
return total;
}
public static IEnumerable<Product> FilterByCategory(this IEnumerable<Product> productEnum,
string categoryParam)
{
foreach (Product prod in productEnum)
{
if (prod.Category == categoryParam)
{
yield return prod;
}
}
}
}
}