75 lines
2.4 KiB
C#
75 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using automatically_implemented_properties;
|
|
|
|
namespace automatically_implemented_properties
|
|
{
|
|
class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
// create and populate Shopping Cart, implementing IEnumerable<Product> interface
|
|
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.50M},
|
|
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
|
|
}
|
|
};
|
|
|
|
IEnumerable<Product> filteredProducts = products.Filter(prod =>
|
|
prod.Category == "Soccer" ||
|
|
prod.Price > 20);
|
|
|
|
foreach (Product prod in filteredProducts)
|
|
{
|
|
Console.WriteLine("Name: {0}, Price {1:c}", prod.Name, prod.Price);
|
|
}
|
|
|
|
decimal total = products.FilterByCategory("Soccer").TotalPrices();
|
|
Console.WriteLine("Filtered total: {0:c}", total);
|
|
}
|
|
|
|
}
|
|
|
|
public static class MyExtensionMethod
|
|
{
|
|
public static decimal TotalPrices(this IEnumerable<Product> productEnum)
|
|
{
|
|
decimal total = 0;
|
|
foreach (Product prod in productEnum)
|
|
{
|
|
total += prod.Price;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
public static IEnumerable<Product> Filter(this IEnumerable<Product> productEnum,
|
|
Func<Product, bool> selectorParam)
|
|
{
|
|
foreach (Product prod in productEnum)
|
|
{
|
|
if (selectorParam(prod))
|
|
{
|
|
yield return prod;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |