Most applications retain lists of things, and a common task is to find an item in that list. The following class illustrates three ways to find an item in a generic list:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Lambdas
{
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
}
public List<Book> Books { get; private set; }
public Lambdas()
{
Books = new List<Book> {
new Book { Title = "Pro ASP.Net MVC Framework", Author = "Steven Sanderson", Price = 49.99 },
new Book{ Title = "Pro Silverlight 2 in C# 2008", Author = "Matthew MacDonald", Price = 49.99},
new Book{ Title = "Pro VB 2008 and the .Net 3.5 Platform", Author = "Andrew Troelsen", Price = 59.99 }
};
}
/// <summary>
/// Returns a book using a traditional loop
/// </summary>
private Book FindUsingTraditionalLoop(string title)
{
Book foundBook = null;
foreach (var b in this.Books)
{
if (b.Title == title)
{
foundBook = b;
break;
}
}
return foundBook;
}
/// <summary>
/// Returns the book using a Linq expression
/// </summary>
private Book FindUsingLinq(string title)
{
var query = from b in this.Books
where b.Title == title
select b;
return query.Count() > 0 ? query.ToList()[0] : null;
}
/// <summary>
/// Returns the book using a Lambda expression
/// </summary>
private Book FindUsingLambda(string title)
{
return this.Books.FirstOrDefault(b => b.Title == title);
}
public void Test()
{
Console.WriteLine("Found: {0}", this.FindUsingTraditionalLoop("Pro Silverlight 2 in C# 2008").Author);
Console.WriteLine("Found: {0}", this.FindUsingLinq("Pro Silverlight 2 in C# 2008").Author);
Console.WriteLine("Found: {0}", this.FindUsingLambda("Pro Silverlight 2 in C# 2008").Author);
}
}
}
As these examples show, you can save time reading and writing your code by using Lambda expressions to find items in a list.
For VB programmers, the syntax of the Lambda expression looks like this:
return Me.Books.FirstOrDefault(Function(b) b.Title = title)