Creating Lambda Extension Methods

by David Kiff 18. March 2009 20:08

There are lots of blogs on Extension Methods and Lambda Expressions; however I haven’t seen many blogs looking at combining the two! This is the aim of this Article. I will replicate the Where extension method for IEnumerable<T> to demonstrate an example.

Take the following code:

public class Person
{
  public string Forename { get; set; }
  public string Surname { get; set; }
  public int Age { get; set; }
}
static class Program
{
    static void Main(string[] args)
    {
        List peopleList = new List
        {
          new Person{ Forename = "David", Surname="Kiff", Age=23},
          new Person{ Forename = "John", Surname="Smith", Age=20},
        };
        IEnumerable results = peopleList.Where(p => p.Forename.ToLower().Equals("david"));
    }
}

The code above creates a generic list with two people. List<T> implements IEnumerable<T> so there is an extension method available called “Where”. The where extension method takes a function and returns an IEnumerable<T> which are the results. The following implementation shows how such a method could be constructed:

public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> list, Func<T, bool> function)
{
  IList<T> resultList = new List<T>();
  foreach (var item in list)
  {
      if (function.Invoke(item))
      {
          resultList.Add(item);
      }
  }
return resultList;
}

This method goes through the enumeration and invokes the lambda expression. Notice that the extension method takes a Func<T, bool>, the T is the type that is used within the expression. In this case it’s the same type that is found in the enumerable. The bool is the return type from the expression so the following lambda expression can be passed in:

person => person.Forename.Equals(“David”)

This takes a person (the T in our Func<T, bool>) and the expression evaluates to a boolean type. If the function returns true then we know that we have a match and can add the item (in our case Person) to an internal list. When every item has been iterated over the internal resultList can be returned.

Download Code

Tags:

C#-3.0

Comments

10/15/2009 5:43:18 AM #

Anonymous

Do you have any more info on this?

Anonymous United States

10/15/2009 6:04:18 AM #

Anonymous

Do you make money out of this blog? just curious

Anonymous United States

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading