29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

using System.Collections.Generic;<br />

namespace LanguageFeatures.Models {<br />

public static class MyExtensionMethods {<br />

public static decimal TotalPrices(this IEnumerable<br />

productEnum) {<br />

decimal total = 0;<br />

foreach (Product prod in productEnum) {<br />

total += prod.Price;<br />

}<br />

return total;<br />

}<br />

public static IEnumerable FilterByCategory(<br />

this IEnumerable productEnum, string<br />

categoryParam) {<br />

}<br />

}<br />

}<br />

foreach (Product prod in productEnum) {<br />

if (prod.Category == categoryParam) {<br />

yield return prod;<br />

}<br />

}<br />

This extension method, called FilterByCategory, takes an additional parameter that allows me to inject a filter<br />

condition when I call the method. Those Product objects whose Category property matches the parameter are returned<br />

in the result IEnumerable and those that do not match are discarded. Listing 4-18 shows this method being<br />

used.<br />

Listing 4-18. Using the Filtering Extension Method in the HomeController.cs File<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Web.Mvc;<br />

using LanguageFeatures.Models;<br />

namespace LanguageFeatures.Controllers {<br />

public class HomeController : Controller {<br />

public string Index() {<br />

return "Navigate to a URL to show an example";<br />

}<br />

// ... other action methods omitted for brevity...<br />

public ViewResult UseFilterExtensionMethod() {<br />

IEnumerable products = new ShoppingCart {<br />

Products = new List {<br />

new Product {Name = "Kayak", Category = "Watersports",<br />

90

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!