9.11. Performing Multiple Operations on a List Using Functors

Problem

You want to be able to perform multiple operations on an entire collection of objects at once, while keeping the operations functionally segmented.

Solution

Use a functor (or function object, as it is also known) as the vehicle for transforming the collection. A functor is any object that can be called as a function. Examples of this are a delegate, a function, a function pointer, or even an object that defines operator() for us C/C++ converts.

Needing to perform multiple operations on a collection is a reasonably common thing in software. Let's say that you have a stock portfolio with a bunch of stocks in it. Your StockPortfolio class would have a List of Stock object and would be able to add stocks:

 public class StockPortfolio : IEnumerable<Stock> { List<Stock> _stocks; public StockPortfolio( ) { _stocks = new List<Stock>( ); } public void Add(string ticker, double gainLoss) { _stocks.Add(new Stock( ) {Ticker=ticker, GainLoss=gainLoss}); } public IEnumerable<Stock> GetWorstPerformers(int topNumber) { return _stocks.OrderBy( (Stock stock) => stock.GainLoss).Take(topNumber); } public void SellStocks(IEnumerable<Stock> stocks) { foreach(Stock s in stocks) _stocks.Remove(s); } public void PrintPortfolio(string title) { Console.WriteLine(title); _stocks.DisplayStocks( ); } #region IEnumerable<Stock> Members public IEnumerator<Stock> GetEnumerator( ) { return _stocks.GetEnumerator( ); } #endregion #region IEnumerable ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.