How to use Lambda Expressions

Until I recently started working at Chase Software I hadn’t really dived to deep into the C# 3.0 features. I really wish I had though because man it would’ve cut down so much code at my previous job. A colleague of mine has taught me so much that I am now looking a lot deeper into C# 3 features. Just in time before C# 4.0 is released! One of the first things I learned to get the hang of is Lambda expressions. Lambdas are inline expressions. These expressions are mainly used in conjunction with LiNQ and thus mostly on IQueryable and IEnumerable collections. Here is an example on how it can cut a lot of code out of you work.

Assume we have a basic class that contains a Name, ID and AwesomeScore for Users.

public class Users
{
public int ID {get; set;}
public string Name {get; set;}
public int AwesomeScore {get; set;}
}

So as you can see there’s nothing difficult about that. Its a basic class definition. So lets create a basic console application and fill a List of Users so we can work with that:

public static void Main(string[] args)
{
// Create and populate new list of Users
List<Users> failBoyUsers = new List<Users>();
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = "FailBoy", ID = 1 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = "Rathlan", ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 9, Name = "Joe", ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 1, Name = "newbie", ID = 4 });
}

So here we create a Generic List Collection of Users. So our failBoyUsers collection now contains 4 users with varying scores. Now, originally before the wonders of learning how to use Lambda’s, I would’ve done the following to return the users with an AwesomeScore of 8 or over:

public static List GetAwesomestPeople(List<Users> usersToSort)
{
List<Users> returnList = new List<Users>();

foreach (Users userItem in usersToSort)
{
if (userItem.AwesomeScore >= 8 )
{
returnList.Add(userItem);
}
}

return returnList;
}

So yeah, that was me, FailBoy being very intelligent. Now, that same functionality using Lambda’s.

public static IQueryable GetAwesomestPeopleLAMBDA(IQueryable usersToSort)
{
return usersToSort.Where(user => user.AwesomeScore >= 8).AsQueryable();
}

Thats right! Using Lambda’s its a single line. So lets look at that line, I pass in the usersToSort as IQueryable instead of the List. Converting from the List to IQueryable is as easy as passing the List parameter in and simply adding .AsQueryable() to the end of the parameter name! So it would be called as :

IQueryable awesomeOkes = GetAwesomestPeopleLAMBDA(failBoyUsers.AsQueryable());

Then I use the .Where() method which is an extension method on the IQueryable collection class and as such on the List<> class since List<> inherits from IEnumerable and IEnumerable inherits from IQueryable. The fun comes in where I pass the argument into the .Where() method.

user => user.AwesomeScore >= 8

Here I am declaring a new variable called user. The variable is an instance of the Collection we want to sort, in this case usersToSort. the “=>” is what is referred to as the Lambda operator. After the Lambda operator we specify our condition. In this as we only want the users with an AwesomeScore of 8 or higher. I then append the

.AsQueryable()

because we want to return the resultset as an IQueryable Collection of Users.

Using Lambda’s I’m condensed 9 lines of code into 1 line of code. And the less you need to code, the more time you save! I hope this is helpful to you! I’ve included the full code below.

FailBoy

3 Comments

  1. AndrewJacksonZA
    Posted July 28, 2009 at 10:48 AM | Permalink

    You need to specify the type of List that you want to create. Try changing it to:

    List failBoyUsers = new List();
    

    Cheers,
    AJ

  2. AndrewJacksonZA
    Posted July 28, 2009 at 10:57 AM | Permalink

    Ah. I see what went wrong. Replace “[[" and "]]” with opening and closing angled brackets respectively:

    List[[Users]] gameUsers = new List[[Users]]();
    

    Cheers,
    AJ

  3. FailBoy
    Posted July 28, 2009 at 11:15 AM | Permalink

    thanks for spotting that

One Trackback

  1. By FailBoy » LINQ: Distinct method on July 27, 2009 at 9:45 PM

    [...] RSS « How to use Lambda Expressions [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*