1 / 41

Getting the Most from Lambda Expressions

Getting the Most from Lambda Expressions. Deborah Kurata President InStep Technologies, Inc Session Code: DTL315. Deborah Kurata is. Consultant and President of: InStep Technologies, Inc. Author of: Doing Objects in VB 2005 Best Kept Secrets in .NET Software designer/developer

johnavon
Télécharger la présentation

Getting the Most from Lambda Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Getting the Most from Lambda Expressions Deborah Kurata President InStep Technologies, Inc Session Code: DTL315

  2. Deborah Kurata is... • Consultant and President of:InStep Technologies, Inc. • Author of: • Doing Objects in VB 2005 • Best Kept Secrets in .NET • Software designer/developer • INETA Speaker • Microsoft MVP • DeborahK@insteptech.com

  3. InStep Technologies is... • Consulting • Mentoring services to get you started and keep you going with .NET • Strategic software consulting and training services • Application architecture and design • Custom software development of Windows and Web-based applications • Web site: www.insteptech.com

  4. You Are... • Using Generic Lists • List(Of Customer) • List<Customer> • Using Lambda Expressions • Just getting started/new to them • Use them once in a while • Use them everyday

  5. This Presentation is … • Fun with Lambda Expressions • What are Lambda Expressions? • Lambdas as Generic Delegates • Lambdas as Callable Entities • Lambdas as Callbacks

  6. Generic Lists • Class Customer • Manages a single customer • Customer properties • Customer methods • Class Customers • Manages the list of customers • List(Of Customer) • List<Customer>

  7. demo Fun With Lambda Expressions

  8. Lambda Calculus • “Formal system designed to investigate function definition, function application, and recursion.” • Wikipedia

  9. What are Lambda Expressions? • New in Visual Basic 9 and C# 3.0 (VS 2008) • Unnamed, inline functions • Single statement • Multiple statement (C# only; coming in VB 10) • Used wherever delegates are required

  10. What is a Delegate? • An object that holds a reference to a method with a particular parameter list and return type • Like object-oriented, type-safe function pointer • Make it possible to treat methods as entities • Assign to variables • Pass as parameters

  11. Classic Delegate Example: Events // Passes the method to the new delegate HelloButton.Click += new EventHandler(HelloButton_Click); ' AddressOf assigns the address of the ' method to the delegate AddHandler HelloButton.Click, _ AddressOf HelloButton_Click

  12. Using Lambda Expressions // C# HelloButton.Click += (s, ev) => MessageBox.Show("Hello World"); ' VB: AddHandler HelloButton.Click, _ Function(s, ev) _ MessageBox.Show("Hello World")

  13. Defining Delegates • Named method • Anonymous method (C# 2.0) • Lambda expression (C# 3.0 and VB 9)

  14. Lambda Expression Syntax - VB ' General syntax: Dim foundCustomer as Customer = _ allCust.First(Function(c as Customer) _ c.CustomerId = 4) ' With inferred typing: Dim foundCustomer = _ allCust.First(Function(c) _ c.CustomerId = 4)

  15. Lambda Expression Syntax – C# ' General syntax: Customer foundCustomer = allCust.First((Customer c) => c.CustomerId == 4); ' With inferred typing: varfoundCustomer = allCust.First(c => c.CustomerId == 4);

  16. Lambda Multiline Syntax – C# var foundCustomer = allCust.First(c => { Debug.WriteLine(c.FullName); if (c.CustomerId == 4) return true; else return false; });

  17. Features that Use Delegates • Event handlers • Enumerable class methods • Extension methods of IEnumerable(T) • Examples: Aggregate, All, Any, FirstOrDefault • LINQ methods • Used by LINQ • Examples: OrderBy, Where, GroupBy

  18. Lambdas as Generic Delegates • Generic delegates were new in .NET 2.0 • Predicate Delegates • Action Delegates • Func Delegates

  19. Predicate Delegate • Predicate: “An operator or function which returns a Boolean value” - Wikipedia • Encapsulates a method that evaluates to True or False • Takes one parameter

  20. Example: Predicate Delegate ' VB: Dim foundCustomer = _ Array.Find(custArray, Function(c) _ c.LastName.StartsWith("K")) // C#: varfoundCustomer = Array.Find(custArray, c => c.LastName.StartsWith("K"));

  21. demo Predicate Delegates

  22. Action Delegate • Encapsulates a method that does not return a value • Sub in VB • void in C# • Takes up to four parameters

  23. Example: Action Delegate ' VB: Can only use named methods allCust.ForEach(AddressOfWriteToDebug) // C#: allCust.ForEach(c => Debug.WriteLine(c.FullName));

  24. demo Action Delegates

  25. Func Delegate • Encapsulates a method that returns a value • Takes up to 4 parameters and a return value • Last parameter is the return value • Func<int, int, string> • Func(Of Integer, Integer, String)

  26. Example: Func Delegate ' VB: Dim total = allCust.Sum(Function(c) _ c.SalesTotal) // C#: var total = allCust.Sum(c => c.SalesTotal);

  27. demo Func Delegates

  28. Lambdas as Callable Entities • Lambda expressions can be assigned to a delegate variable • Lambda expression is executed when the delegate is executed

  29. Example: Assignment ' VB: Infers the type Dim f = _ Function(x as Integer) (x + x).ToString() Debug.WriteLine(f(5)) Debug.WriteLine(f(10)) // C#: Func<int,string> f = x => (x + x).ToString(); Debug.WriteLine(f(5)); Debug.WriteLine(f(10));

  30. Lambda Expression Execution • Lambda expressions are executed when they are called, not when they are constructed • Local variables used in a lambda expression are “captured” or “lifted” • Variable value used is the value at execution time • Variable lifetime extends to the lifetime of the delegate

  31. Example: Local Variables // C#: int y = 0; Func<int,string> f = x => (x + y).ToString(); y = 10; Debug.WriteLine(f(5)); ' VB: Dim y As Integer = 0 Dim f As Func(Of Integer, String) = _ Function(x) (x + y).ToString() y = 10 Debug.WriteLine(f(5))

  32. demo Callable Entities

  33. Lambdas as Callbacks • Callback • “Executable code that is passed as an argument to other code” • Passes a function to a function • A delegate does not know or care about the class of the method it is referencing • No need to reference the class that defined the method

  34. demo Callbacks

  35. Getting the Most from Lambdas • Use Lambda expressions for • Writing inline functions • Calling LINQ methods • Calling extension methods that take a delegate • Creating callable functions • Performing callbacks

  36. Resources • www.microsoft.com/teched Sessions On-Demand & Community • www.microsoft.com/learning • Microsoft Certification & Training Resources • http://microsoft.com/technet • Resources for IT Professionals • http://microsoft.com/msdn Resources for Developers www.microsoft.com/learning Microsoft Certification and Training Resources

  37. Related Content DTL336 Future Directions for Visual Basic Presenter(s): Jonathan Aneja, Anders Hejlsberg DTL402 How LINQ Works: A Deep Dive into the Microsoft Visual Basic and C# Implementations Presenter: Jonathan Aneja

  38. Track Resources Visit the DPR TLC for a chance to win a copy of Visual Studio Team Suite. Daily drawing occurs every day in the TLC at 4:15pm. Stop by for a raffle ticket http://www.microsoft.com/visualstudio http://www.microsoft.com/visualstudio/en-us/products/teamsystem/default.mspx Please visit us in the TLC blue area

  39. Complete an evaluation on CommNet and enter to win!

  40. © 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related