Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

July 2, 2009

Lambda Expressions: Finding Differences in Two Lists

Filed under: C#,Lambda Expressions @ 7:19 pm

One of my favorite features in .NET 3.5 is lambda expressions.

[To begin with an overview of lambda expressions, start here.]

This example demonstrates how to use lambda expressions:

  • To compare items in two lists and find which items in one list are not in the other. For example: {1, 2, 3}, {2, 3, 4}. {1} is only in the first list.
  • To display the contents of the resulting set.

First, define two lists:

List<int> list1 = new List<int>() { 1, 6, 8 };
List<int> list2 = new List<int>() { 2, 6 };

The following lambda expression finds all of the items that are only in the first list:

Func<IEnumerable<int>> exceptionFunction = () => list1.Except(list2);

This is a Func delegate which returns an IEnumerable<int>. There are no arguments passed into the function, hence the empty parenthesis (). The => is the lambda operator. The remaining code uses the Except method of the list to find the items not in the second list.

The following lambda expression displays the resulting items:

Action displayList =
    () => exceptionFunction().ToList().ForEach(i => Debug.WriteLine(i));

This one is an Action delegate that takes no parameters. It first takes the IEnumerable result from the exceptionFunction, converts it to a list, then writes each item to the Debug window.

Call the displayList method to try this out:

displayList(); // Result 1,8

Calling displayList calls exceptionFunction which operates on the two lists. This will display 1 and 8 to the Debug window.

You can then change the list and see the new results:

list2 = new List<int>() { 1, 4 };
displayList();  // Result = 6, 8

Since the code in the lambda expressions is not executed until it is called, this call to displayList recognizes the current values of the lists. So you get new results.

You can change the other list and see the new results:

list1 = new List<int>() { 3, 4, 9 };
displayList();  // Result = 3, 9


1 Comment

  1.   Steve — October 13, 2009 @ 3:47 am    Reply

    exceptionFunction looks like it’s some function that handles Exceptions :p

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs