5.1.5 Creating Filtering Extension Methods
parent
ec983ff21c
commit
61cf1cbfaf
|
@ -14,28 +14,20 @@ namespace automatically_implemented_properties
|
||||||
{
|
{
|
||||||
Products = new List<Product>
|
Products = new List<Product>
|
||||||
{
|
{
|
||||||
new Product {Name = "Kayak", Price = 275M},
|
new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
|
||||||
new Product {Name = "Lifejacket", Price = 48.95M},
|
new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
|
||||||
new Product {Name = "Soccer ball", Price = 19.50M},
|
new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
|
||||||
new Product {Name = "Corner flag", Price = 34.95M}
|
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// create and populate an array of Product objects, implementing IEnumerable<Product> interface
|
foreach (Product prod in products.FilterByCategory("Soccer"))
|
||||||
Product[] productArray =
|
|
||||||
{
|
{
|
||||||
new Product {Name = "Kayak", Price = 275M},
|
Console.WriteLine("Name: {0}, Price {1:c}", prod.Name, prod.Price);
|
||||||
new Product {Name = "Lifejacket", Price = 48.95M},
|
}
|
||||||
new Product {Name = "Soccer ball", Price = 19.50M},
|
|
||||||
new Product {Name = "Corner flag", Price = 34.95M}
|
decimal total = products.FilterByCategory("Soccer").TotalPrices();
|
||||||
};
|
Console.WriteLine("Filtered total: {0:c}", total);
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -51,5 +43,17 @@ namespace automatically_implemented_properties
|
||||||
}
|
}
|
||||||
return total;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue