Print Shortlink

C#- Revisiting Lambda Expressions

Though plenty of articles have been written about Lambda expressions in C#, still feel most of the developers continue to build .NET applications using C# 1.0. I had an opportunity to discuss lambda expressions with a group of developers.

We created a simple list of string values and wanted to print the strings that end with letter ‘y’. We discussed various ways to implement this. We started off with the traditional approach of using for-each loop and moved on to use lambda expressions. Given below is the code that we wrote.

//Approach - I
 List<string> langs = new List<string>() { "Java","C#","Ruby","Groovy","Scala"};
 foreach (string lang in langs)
 {
      if(lang.EndsWith("y"))
          Console.WriteLine(lang);
 }
//Approach - II
bool FindLanguages(string lang)
{
   return lang.EndsWith("y");
}
List<string> langs = new List<string>() { "Java","C#","Ruby","Groovy","Scala"};
foreach (string lang in langs)
{
     if (FindLanguages(lang))
         Console.WriteLine(lang);
}
//Approach - III
bool FindLanguages(string lang)
{
   return lang.EndsWith("y");
}
List<string> langs = new List<string>() { "Java","C#","Ruby","Groovy","Scala"};
var result = langs.FindAll(FindLanguages);
foreach (var item in result)
{
    Console.WriteLine(item);
}
//Approach - IV
List<string> langs = new List<string>() { "Java","C#","Ruby","Groovy","Scala"};
Predicate<string> FindLanguages = lang => lang.EndsWith("y");
var result = langs.FindAll(FindLanguages);
foreach (var item in result)
{
    Console.WriteLine(item);
}
//Approach - V
List<string> langs = new List<string>() { "Java","C#","Ruby","Groovy","Scala"};
var result = langs.Where(lang=>lang.EndsWith("y"));
foreach (var item in result)
{
    Console.WriteLine(item);
}

The last two approaches (IV and V) show the use of lambda expressions.

Leave a Reply