Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » C# Language » Lambda Expressions are Wonderful

Lambda Expressions are Wonderful

Lambda expressions are simple to use and make routine tasks such as sorting or filtering Lists much easier.

Page Views : 8189
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Lambda expressions are part of .Net 3.0. They are used extensively in Linq, but they can also be used on their own. With Lambda expressions, filtering and sorting Lists has become a lot easier.

In my examples, I'm going to filter and sort Lists of Employee objects:

public class Employee

{
    public string FirstName {set; get;}
    public string LastName {set; get;}
    public decimal Salary {set; get;}
    public bool IsManager {set; get;}
}

FindAll( )

Suppose I have a List of Employees, and I want to find all the managers.  At one point I would have written code like this:

List<Employee> managers = new List<Employee>( );
foreach (Employee employee in employees)
{
    if (employee.IsManager == true)
        managers.Add(employee);
}

The new syntax with Lambda expressions is clean and simple:

 List<Employee> managers = employees.FindAll(employee => employee.IsManager == true);

Note that the term "employee" was used to make things clear.  I could have used any other name.  For example:

 List<Employee> managers = employees.FindAll(e => e.IsManager == true);

Where( )

Where( ) works exactly the same way as FindAll( ).  In some cases, using Where( ) instead of FindAll( ) can make your code easier to understand.  Here, for example, is a different way to find all the managers:

using System.Linq;

foreach (Employee employee in employees.Where(e => e.IsManager == true))
{
    // do something
}

Find( )

Find( ) returns the first object in a list which meets my search criteria.  If no object meets my criteria, it returns null.

Employee firstManager = employees.Find(employee => employee.IsManager == true);

if (firstManager == null)
    Console.WriteLine("No managers found in list.");

ForEach( )

ForEach( ) can be used to perform an operation on each item in a List.  In this example we are adding 100 to the Salary of each Employee:

 employees.ForEach(e => e.Salary += 100);

OrderBy( )  and  OrderByDescending( )

OrderBy( ) returns a List sorted in ascending order.   OrderByDescending( ) returns a List sorted in descending order.  This only works if there is an appropriate method to do the comparison.  For basic data types (e.g., string, int, decimal, etc.), Lambda expressions make sorting easy:

using System.Linq; 

List
<Employee> sortedList = employees.OrderBy(e => e.Age).ToList();

Note that the original List, employees, is unchanged.  Of course, you could sort the employees List itself as follows:

 employees = employees.OrderBy(e => e.Age).ToList();

To sort in descending order:

 List<Employee> sortedList = employees.OrderByDescending(e => e.Age).ToList();

Sort( )

Sort( ) provides an alternative to OrderBy( ):

 employees.Sort((e1, e2) => e1.DOB.CompareTo(e2.DOB));

Note that Sort( ) operates on the orginal List, employees.  That is, there is no need to do this:

 employees = employees.Sort((e1, e2) => e1.DOB.CompareTo(e2.DOB));

because employees is already sorted.

Getting Fancy

If I make an enum like this:

 public enum SortOrder { Ascending, Decending }

and I add this method to the Employee class:

public static void Sort<TKey>(ref List<Employee> list, Func<Employee, TKey> sortKey, 
    SortOrder sortOrder)
{
    if (sortOrder == SortOrder.Ascending)
        list = list.OrderBy(sortKey).ToList();
    else
        list = list.OrderByDescending(sortKey).ToList();
}

Now I can sort my List of Employees like this:

 Employee.Sort(employees, e => e.Salary, SortOrder.Ascending);

or this:

Employee.Sort(employees, e => e.LastName, SortOrder.Descending);


In this article, I've only discussed the use of Lambda expressions to sort and filter Lists of objects.  If that were the only use for Lambda expressions, they would still be a major time saver - a fantastic new addition to .Net.  Lambda expressions, however, have many uses.  Once you get started, you will wonder how you ever managed without them.

Enjoy.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Andrew Fenster
Andrew Fenster is an IT consultant in Cleveland, Ohio.  He has worked as a developer, technical lead or architect on many projects, large and small.  He has consulted for Progressive Insurance, Charles Schwab, OE Connection and National City Bank, among others. 
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Well written article! by Ping On December 2, 2009
Man, I have been serching for something like this for a long time.
You saved me countless hours of coding.
Thank you Andy, good work!

Ping-Fu
Reply | Email | Modify 
Too complex for me by Abdul On December 4, 2009

I did not learn much from this article even though I have 3 years of coding in many languages and databases. I was not able to understand much but I have many years coding  and work in many fields.

Reply | Email | Modify 
Re: Too complex for me by gfw On December 27, 2009
Perhaps you need to try fewer languages and get a better handle on the one or two that you prefer to use the most. If you are doing anything with MS and .Net, Lambda Expressions are here to stay and do indeed make life a little more simple and code mush easier to read.
Reply | Email | Modify 
Good article! by Alan C On December 23, 2009
This article is an example of why I like C# Corner.  It's simple and easy to follow, so I can get a quick introduction to the topic without time-consuming complexity.  Well done!

==============

The feedback mechanism for this site could be improved, however.  The User ID is case-sensitive, which is unusual.  Also when I submitted my comment, the site asked me to log in, the ID I typed didn't match the original case, so was rejected.  I selected the "forgot password" link and got the password, BUT THE SITE THREW AWAY THE COMMENTS I HAD ENTERED!  This wastes peoples' time.
Reply | Email | Modify 
Thanks by gfw On December 27, 2009
Good article and easy to understand.  Thanks.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.