This article and the vb.net and c# downloads are to show how you can use lambda expressions as delegates to perform many functions on System.Collections.Generic.List(T), and in some cases any object that implements IEnumerable with more concise code. Huh? Typically I use Generic.List(T) to hold my object instances, so a lot of the methods I'm going to demonstrate lambda expressions with are exposed on the class Generic.List(T). Some of these methods can be found in other generic lists also so feel free to use them there. In addition, there is now an Enumerable Class in System.Linq. This class holds extension methods that can be used on any object that implements IEnumerable(T). List(T) happens to be one of those classes so in addition to it's own methods, we have access to these extensions methods. What I want to focus on however, is not just the use of all these methods we now access to on List(T). There are tons of code samples out there showing how to use these.
What I would like to really focus on is one of the things that I have found the most useful in the .NET 3.0 release. That is the use of lambda expressions when working with generic lists such as List(T). Using lambda expressions with the different methods found in System.Linq.Enumerable (Extension Methods) and List(T) I am able to do things such as Sort, Filter, Order, Group, Format and perform aggregate functions on my List(T) collection of objects. There's nothing that lambda expressions can do that couldn't be done before, it can just be done with less code now which I am personally a big fan of. Also, it is nice for debugging purposes to keep simple function definitions located were they are used instead of sprawled out in your code. Lambda expression originate form calculus, however by no means do you have to be a Fibonacci or a Pythagoras to figure them out. For people like me, there's a little "understanding curve" but trust me, once you do about 10-15 of these they will start to click.
Let's get started. Say we had a collection of stock objects in a generic list called stocks. Stock has the properties StockID, CurrentPrice, PriceChange and instance of Industry. How can we output to a console window all stocks in the collection where the PriceChange was greater than $1.00. There are several ways to accomplish this task. The first three samples below show how we can accomplish this using a (1) Linq query, (2) delegate, and (3) lambda expression. Please note that using the Linq query and the lambda expression both allow you to do the same thing with a single line of code in most cases. However for me, especially with C# I prefer the conciseness of the lambda expressions. After contrasting three different ways to accomplish the first task I will begin to demonstrate the methods I find most useful with some real world scenarios on how to use them. These samples will all be done using lambda expressions and will not be contrasted with the first two approaches.
C# Sample Code
VB.Net Sample Code
C# Full Project Download
VB.Net Full Project Download
C# Code Sample
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- class Program
- {
-
-
-
-
-
- private static bool GetDollarPlusGainers(Stock stock)
- {
- return stock.PriceChange > 1.00;
- }
-
-
-
-
-
-
-
-
- private static void OutputFormattedStockToDisplay(Stock stock, ConsoleColor? consoleColor)
- {
- Console.ForegroundColor = consoleColor.GetValueOrDefault(ConsoleColor.Yellow);
-
- Console.WriteLine("StockID: " + stock.StockID);
- Console.WriteLine("Symbol: " + stock.Symbol);
- Console.WriteLine("Current Price: " + String.Format("{0:c}", stock.CurrentPrice));
- Console.WriteLine("Price Change: " + String.Format("{0:c}", stock.PriceChange));
- Console.WriteLine("IndustryID: " + stock.Industry.IndustryID);
- Console.WriteLine("Industry Name: " + stock.Industry.Name);
- Console.WriteLine("");
- Console.WriteLine("");
- }
-
-
-
- static void Main(string[] args)
- {
-
- List<Stock> stocks = DataHelper.GetTestData();
-
-
-
-
-
-
- foreach (Stock stock in from s in stocks where s.PriceChange > 1.00 select s)
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.FindAll(GetDollarPlusGainers))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.FindAll(s => s.PriceChange > 1.00))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
- Console.WriteLine("Total number of stocks: " + stocks.Count());
- Console.WriteLine("Number of stocks > $100: " + stocks.FindAll(s => s.CurrentPrice > 100).Count());
- Console.WriteLine("Number of stocks <= $100: " + stocks.FindAll(s => s.CurrentPrice <= 100).Count());
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Current Max Stock Price: " + stocks.Max(s => Convert.ToDouble(s.CurrentPrice)));
- Console.WriteLine("Current Max Stock Price: " + stocks.Min(s => Convert.ToDouble(s.CurrentPrice)));
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Avg Current Stock Price: " + stocks.Average(s => Convert.ToDouble(s.CurrentPrice)));
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OrderBy(s => s.Symbol))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OrderBy(s => s.Industry.Name).ThenBy(s => s.Symbol))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OrderByDescending(s => s.Symbol))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- stocks.Sort(delegate(Stock x, Stock y) { return x.Symbol.CompareTo(y.Symbol); });
-
- foreach (Stock stock in stocks)
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- Console.WriteLine("The stocks collection contains stocks > $100: " + stocks.Contains(stocks.Find(s => s.CurrentPrice > 100)));
- Console.WriteLine("The stocks collection contains stocks > $150: " + stocks.Contains(stocks.Find(s => s.CurrentPrice > 150)));
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).TakeWhile(s => s.CurrentPrice > 50))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-");
-
- foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).TakeWhile(s => s.CurrentPrice > 100))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-");
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).Take(3))
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- foreach (Stock stock in stocks.OfType<Stock>())
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- Console.WriteLine("All stocks are > 10.00: " + stocks.All(s => s.CurrentPrice > 10));
- Console.WriteLine("All stocks are > .01: " + stocks.All(s => s.CurrentPrice > .01));
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
-
- stocks.RemoveAll(c => c.CurrentPrice > 25);
-
- foreach (Stock stock in stocks)
- {
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green);
- }
-
- Console.ReadLine();
-
-
-
-
-
-
-
-
-
- foreach (IGrouping<string, Stock> industry in stocks.GroupBy(s => s.Industry.Name))
- {
- Console.WriteLine(industry.Average(s => s.CurrentPrice));
- }
-
- Console.ReadLine();
- }
- }
using System;using System.Collections.Generic;using System.Linq;class Program{ /// <summary> /// Determines if stock's PriceChange is greater than zero. /// </summary> /// <param name="stock">Stock to check.</param> /// <returns>Boolean indicating if stock's PriceChange is greater than zero.</returns> private static bool GetDollarPlusGainers(Stock stock) { return stock.PriceChange > 1.00; } /// <summary> /// Outputs formatted Stock. /// </summary> /// <param name="stock">Stock to format.</param> /// <param name="consoleColor">Color to format Stock with.</param> private static void OutputFormattedStockToDisplay(Stock stock, ConsoleColor? consoleColor) { Console.ForegroundColor = consoleColor.GetValueOrDefault(ConsoleColor.Yellow); Console.WriteLine("StockID: " + stock.StockID); Console.WriteLine("Symbol: " + stock.Symbol); Console.WriteLine("Current Price: " + String.Format("{0:c}", stock.CurrentPrice)); Console.WriteLine("Price Change: " + String.Format("{0:c}", stock.PriceChange)); Console.WriteLine("IndustryID: " + stock.Industry.IndustryID); Console.WriteLine("Industry Name: " + stock.Industry.Name); Console.WriteLine(""); Console.WriteLine(""); } static void Main(string[] args) { // get some stocks List<Stock> stocks = DataHelper.GetTestData(); /*********************************************************************** * 1. Get cStocks with PriceChange > 1.00 using linq query ***********************************************************************/ foreach (Stock stock in from s in stocks where s.PriceChange > 1.00 select s) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 2. Get cStocks with PriceChange > 1.00 using delegate * * Method(s): FindAll ***********************************************************************/ foreach (Stock stock in stocks.FindAll(GetDollarPlusGainers)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 3. Get cStocks with PriceChange > 1.00 using Lambda Expression * * Method(s): FindAll ***********************************************************************/ foreach (Stock stock in stocks.FindAll(s => s.PriceChange > 1.00)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 4. 'Count' Stock's in stocks > $100 and <=$100 * * Method(s): FindAll, Count ***********************************************************************/ Console.WriteLine("Total number of stocks: " + stocks.Count()); Console.WriteLine("Number of stocks > $100: " + stocks.FindAll(s => s.CurrentPrice > 100).Count()); Console.WriteLine("Number of stocks <= $100: " + stocks.FindAll(s => s.CurrentPrice <= 100).Count()); Console.ReadLine(); /*********************************************************************** * 5. 'Max' and 'Min' by Stock.Price * * Method(s): Max, Min ***********************************************************************/ Console.WriteLine("Current Max Stock Price: " + stocks.Max(s => Convert.ToDouble(s.CurrentPrice))); Console.WriteLine("Current Max Stock Price: " + stocks.Min(s => Convert.ToDouble(s.CurrentPrice))); Console.ReadLine(); /*********************************************************************** * 6. 'Average' CurrentPrice of all Stocks in stocks * * Method(s): Average ***********************************************************************/ Console.WriteLine("Avg Current Stock Price: " + stocks.Average(s => Convert.ToDouble(s.CurrentPrice))); Console.ReadLine(); /*********************************************************************** * 7. 'OrderBy' Stock.Symbol * * Method(s): OrderBy ***********************************************************************/ foreach (Stock stock in stocks.OrderBy(s => s.Symbol)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 8. 'OrderBy' Stock.Industry.Name, 'ThenBy' Stock.Symbol * * * Method(s): OrderBy, ThenBy ***********************************************************************/ foreach (Stock stock in stocks.OrderBy(s => s.Industry.Name).ThenBy(s => s.Symbol)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 9. 'OrderByDescending' Stock.Symbol * * * Method(s): OrderByDescending ***********************************************************************/ foreach (Stock stock in stocks.OrderByDescending(s => s.Symbol)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 10. 'Sort' stocks by Symbol (ASC) * * * Method(s): Sort, CompareTo ***********************************************************************/ stocks.Sort(delegate(Stock x, Stock y) { return x.Symbol.CompareTo(y.Symbol); }); foreach (Stock stock in stocks) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 11. Does stocks 'Contain' any Stocks.CurrentPrice > $100, $150 * * * Method(s): Contains, Find ***********************************************************************/ Console.WriteLine("The stocks collection contains stocks > $100: " + stocks.Contains(stocks.Find(s => s.CurrentPrice > 100))); Console.WriteLine("The stocks collection contains stocks > $150: " + stocks.Contains(stocks.Find(s => s.CurrentPrice > 150))); Console.ReadLine(); /*********************************************************************** * 12. List cStock's in Stocks.CurrentPrice > $50, $100 * * * Method(s): OrderByDescending, TakeWhile ***********************************************************************/ foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).TakeWhile(s => s.CurrentPrice > 50)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-"); foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).TakeWhile(s => s.CurrentPrice > 100)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-"); Console.ReadLine(); /*********************************************************************** * 13. 'Take' the top 3 stocks by Pricechange * * * Method(s): OrderByDescending, Take ***********************************************************************/ foreach (Stock stock in stocks.OrderByDescending(s => Math.Abs(s.CurrentPrice)).Take(3)) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 14. Elements in stocks that are 'OfType' cStock (all in our case) * * * Method(s): OfType ***********************************************************************/ foreach (Stock stock in stocks.OfType<Stock>()) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 15 Do 'All' cStock's in stocks have CurrentPrice > 10.00, .01 * * * Method(s): All ***********************************************************************/ Console.WriteLine("All stocks are > 10.00: " + stocks.All(s => s.CurrentPrice > 10)); Console.WriteLine("All stocks are > .01: " + stocks.All(s => s.CurrentPrice > .01)); Console.ReadLine(); /*********************************************************************** * 16. 'RemoveAll' cStock's with CurrentPrice > 25.00 * * * Method(s): RemoveAll ***********************************************************************/ stocks.RemoveAll(c => c.CurrentPrice > 25); foreach (Stock stock in stocks) { OutputFormattedStockToDisplay(stock, ConsoleColor.Green); } Console.ReadLine(); /*********************************************************************** * 17. 'Average' CurrentPrice for each Industry 'GroupBy' * * Method(s): GroupBy, Average '***********************************************************************/ foreach (IGrouping<string, Stock> industry in stocks.GroupBy(s => s.Industry.Name)) { Console.WriteLine(industry.Average(s => s.CurrentPrice)); } Console.ReadLine(); }}
VB.Net Code Sample
- Imports System.Collections.Generic
- Imports LinqSamples
-
- Namespace TestHarnass
-
- Module Program
-
-
-
-
-
-
-
- Public Function GetDollarPlusGainers(ByVal p_stock As cStock) As Boolean
-
- Return p_stock.PriceChange > 1.0
-
- End Function
-
-
-
- Private Sub OutputFormattedStockToDisplay(ByVal p_Stock As cStock, ByVal p_ConsoleColor? As ConsoleColor)
-
- Console.ForegroundColor = p_ConsoleColor.GetValueOrDefault(ConsoleColor.Yellow)
-
- Console.WriteLine("StockID: " & p_Stock.StockID)
- Console.WriteLine("Symbol: " & p_Stock.Symbol)
- Console.WriteLine("Current Price: " & String.Format("{0:c}", p_Stock.CurrentPrice))
- Console.WriteLine("Price Change: " & String.Format("{0:c}", p_Stock.PriceChange))
- Console.WriteLine("IndustryID: " & p_Stock.Industry.IndustryID)
- Console.WriteLine("Industry Name: " & p_Stock.Industry.Name)
- Console.WriteLine("")
- Console.WriteLine("")
-
- End Sub
-
-
-
- Sub Main()
-
-
- Dim stocks As List(Of cStock) = DataHelper.GetTestData()
-
-
-
-
-
-
- For Each stock As cStock In From s In stocks Where s.PriceChange
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.FindAll(New Predicate(Of cStock)(AddressOf GetDollarPlusGainers))
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.FindAll(Function(s As cStock) s.PriceChange > 1.0)
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Total number of stocks: " & stocks.Count())
- Console.WriteLine("Number of stocks > $100: " & stocks.FindAll(Function(s As cStock) s.CurrentPrice > 100).Count())
- Console.WriteLine("Number of stocks <= $100: " & stocks.FindAll(Function(s As cStock) s.CurrentPrice <= 100).Count())
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Current Max Stock Price: " & stocks.Max(Function(s As cStock) Convert.ToDouble(s.CurrentPrice)))
- Console.WriteLine("Current Min Stock Price: " & stocks.Min(Function(s As cStock) Convert.ToDouble(s.CurrentPrice)))
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Avg Current Stock Price: " & stocks.Average(Function(s As cStock) Convert.ToDouble(s.CurrentPrice)))
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OrderBy(Function(s As cStock) s.Industry.Name)
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OrderBy(Function(s As cStock) s.Industry.Name).ThenBy(Function(s As cStock) s.Symbol)
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) s.Industry.Name)
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- stocks.Sort(Function(x, y) x.Symbol.CompareTo(y.Symbol))
-
- For Each stock As cStock In stocks
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- Console.WriteLine("The stocks collection contains stocks > $100: " & stocks.Contains(stocks.Find(Function(s As cStock) s.CurrentPrice > 100)))
- Console.WriteLine("The stocks collection contains stocks > $150: " & stocks.Contains(stocks.Find(Function(s As cStock) s.CurrentPrice > 150)))
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.CurrentPrice)).TakeWhile(Function(s As cStock) s.CurrentPrice > 50)
-
- Console.WriteLine("The stocks > $50")
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-")
-
- For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.CurrentPrice)).TakeWhile(Function(s As cStock) s.CurrentPrice > 100)
-
- Console.WriteLine("The stocks > $50")
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-")
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.PriceChange)).Take(3)
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each stock As cStock In stocks.OfType(Of cStock)()
-
- Console.WriteLine(stock.Symbol & " is a cStock")
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
- Console.WriteLine("All stocks are > 10.00: " & stocks.All(Function(s As cStock) s.CurrentPrice > 10.0))
- Console.WriteLine("All stocks are > .01: " & stocks.All(Function(s As cStock) s.CurrentPrice > 0.01))
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- stocks.RemoveAll(Function(s As cStock) s.CurrentPrice > 25)
-
- For Each stock As cStock In stocks
-
- OutputFormattedStockToDisplay(stock, ConsoleColor.Green)
-
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- For Each industry As IGrouping(Of String, cStock) In stocks.GroupBy(Function(s As cStock) s.Industry.Name)
- Console.WriteLine(industry.Average(Function(s As cStock) s.CurrentPrice))
- Next
-
- Console.ReadLine()
-
-
-
-
-
-
-
-
-
- Console.WriteLine(String.Join(",", stocks.ConvertAll(Function(s As cStock) s.Symbol).ToArray()))
-
- Console.ReadLine()
-
- End Sub
-
- End Module
-
- End Namespace
Imports System.Collections.GenericImports LinqSamplesNamespace TestHarnass Module Program ''' <summary> ''' Determines if stock's PriceChange is greater than zero. ''' </summary> ''' <param name="p_stock">Stock to check.</param> ''' <returns>Boolean indicating if stock's PriceChange is greater than zero.</returns> ''' <remarks></remarks> Public Function GetDollarPlusGainers(ByVal p_stock As cStock) As Boolean Return p_stock.PriceChange > 1.0 End Function Private Sub OutputFormattedStockToDisplay(ByVal p_Stock As cStock, ByVal p_ConsoleColor? As ConsoleColor) Console.ForegroundColor = p_ConsoleColor.GetValueOrDefault(ConsoleColor.Yellow) Console.WriteLine("StockID: " & p_Stock.StockID) Console.WriteLine("Symbol: " & p_Stock.Symbol) Console.WriteLine("Current Price: " & String.Format("{0:c}", p_Stock.CurrentPrice)) Console.WriteLine("Price Change: " & String.Format("{0:c}", p_Stock.PriceChange)) Console.WriteLine("IndustryID: " & p_Stock.Industry.IndustryID) Console.WriteLine("Industry Name: " & p_Stock.Industry.Name) Console.WriteLine("") Console.WriteLine("") End Sub Sub Main() ' Get some stocks Dim stocks As List(Of cStock) = DataHelper.GetTestData() '*********************************************************************** ' 1. Get cStocks with PriceChange > 1.00 using linq query '*********************************************************************** For Each stock As cStock In From s In stocks Where s.PriceChange OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 2. Get cStocks with PriceChange > 1.00 using delegate ' ' Method(s): FindAll '*********************************************************************** For Each stock As cStock In stocks.FindAll(New Predicate(Of cStock)(AddressOf GetDollarPlusGainers)) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 3. Get cStocks with PriceChange > 1.00 using Lambda Expression ' ' Method(s): FindAll '*********************************************************************** For Each stock As cStock In stocks.FindAll(Function(s As cStock) s.PriceChange > 1.0) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 4. 'Count' cStocks in stocks > $100 and <=$100 ' ' Method(s): FindAll, Count '*********************************************************************** Console.WriteLine("Total number of stocks: " & stocks.Count()) Console.WriteLine("Number of stocks > $100: " & stocks.FindAll(Function(s As cStock) s.CurrentPrice > 100).Count()) Console.WriteLine("Number of stocks <= $100: " & stocks.FindAll(Function(s As cStock) s.CurrentPrice <= 100).Count()) Console.ReadLine() '*********************************************************************** ' 5. 'Max' and 'Min' by cStock.Price ' ' Method(s): Max, Min '*********************************************************************** Console.WriteLine("Current Max Stock Price: " & stocks.Max(Function(s As cStock) Convert.ToDouble(s.CurrentPrice))) Console.WriteLine("Current Min Stock Price: " & stocks.Min(Function(s As cStock) Convert.ToDouble(s.CurrentPrice))) Console.ReadLine() '*********************************************************************** ' 6. 'Average' CurrentPrice of all cStocks in stocks ' ' Method(s): Average '*********************************************************************** Console.WriteLine("Avg Current Stock Price: " & stocks.Average(Function(s As cStock) Convert.ToDouble(s.CurrentPrice))) Console.ReadLine() '*********************************************************************** ' 7. 'OrderBy' cStock.Symbol ' ' Method(s): FindAll, Count '*********************************************************************** For Each stock As cStock In stocks.OrderBy(Function(s As cStock) s.Industry.Name) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 8. 'OrderBy' cStock.Industry.Name, 'ThenBy' cStock.Symbol ' ' Method(s): OrderBy, ThenBy '*********************************************************************** For Each stock As cStock In stocks.OrderBy(Function(s As cStock) s.Industry.Name).ThenBy(Function(s As cStock) s.Symbol) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 9. 'OrderByDescending' cStock.Symbol ' ' Method(s): OrderByDescending '*********************************************************************** For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) s.Industry.Name) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 10. 'Sort' stocks by Symbol (ASC) ' ' Method(s): Sort, CompareTo '*********************************************************************** stocks.Sort(Function(x, y) x.Symbol.CompareTo(y.Symbol)) For Each stock As cStock In stocks OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 11. Does stocks 'Contain' any cStocks.CurrentPrice > $100, $150 ' ' Method(s): Contains, Find '*********************************************************************** Console.WriteLine("The stocks collection contains stocks > $100: " & stocks.Contains(stocks.Find(Function(s As cStock) s.CurrentPrice > 100))) Console.WriteLine("The stocks collection contains stocks > $150: " & stocks.Contains(stocks.Find(Function(s As cStock) s.CurrentPrice > 150))) Console.ReadLine() '*********************************************************************** ' 12. List cStock's in stocks.CurrentPrice > $50, $100 ' ' Method(s): OrderByDescending, TakeWhile '*********************************************************************** For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.CurrentPrice)).TakeWhile(Function(s As cStock) s.CurrentPrice > 50) Console.WriteLine("The stocks > $50") OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-") For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.CurrentPrice)).TakeWhile(Function(s As cStock) s.CurrentPrice > 100) Console.WriteLine("The stocks > $50") OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.WriteLine("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-") Console.ReadLine() '*********************************************************************** ' 13. 'Take' the top 3 stocks by Pricechange ' ' Method(s): OrderByDescending, Take '*********************************************************************** For Each stock As cStock In stocks.OrderByDescending(Function(s As cStock) Math.Abs(s.PriceChange)).Take(3) OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 14. Elements in stocks that are 'OfType' cStock (all in our case) ' ' Method(s): OfType '*********************************************************************** For Each stock As cStock In stocks.OfType(Of cStock)() Console.WriteLine(stock.Symbol & " is a cStock") Next Console.ReadLine() '*********************************************************************** ' 15. Do 'All' cStock's in stocks have CurrentPrice > 10.00, .01 ' ' Method(s): All '*********************************************************************** Console.WriteLine("All stocks are > 10.00: " & stocks.All(Function(s As cStock) s.CurrentPrice > 10.0)) Console.WriteLine("All stocks are > .01: " & stocks.All(Function(s As cStock) s.CurrentPrice > 0.01)) Console.ReadLine() '*********************************************************************** ' 16. 'RemoveAll' cSstock's with CurrentPrice > 25.00 ' ' Method(s): RemoveAll '*********************************************************************** stocks.RemoveAll(Function(s As cStock) s.CurrentPrice > 25) For Each stock As cStock In stocks OutputFormattedStockToDisplay(stock, ConsoleColor.Green) Next Console.ReadLine() '*********************************************************************** ' 17. 'Average' CurrentPrice for each Industry 'GroupBy' ' ' Method(s): GroupBy, Average '*********************************************************************** For Each industry As IGrouping(Of String, cStock) In stocks.GroupBy(Function(s As cStock) s.Industry.Name) Console.WriteLine(industry.Average(Function(s As cStock) s.CurrentPrice)) Next Console.ReadLine() '*********************************************************************** ' 18. Comma Delimited list of all cStock's in stocks ' ' Method(s): ConvertAll, ToArray '*********************************************************************** Console.WriteLine(String.Join(",", stocks.ConvertAll(Function(s As cStock) s.Symbol).ToArray())) Console.ReadLine() End Sub End ModuleEnd Namespace
Useful Links:
MSDN List(T) Methods
MSDN Lambda Expressions (C#)
MSDN Lambda Expressions (VB.Net)
The New Lambda Expressions Feature in C# 3.0 Lambda Expressions