Lambda Expressions in C#

The article demonstrates the C# code examples with lambda expressions. As an illustration, they are done in the .NET interactive notebook installed in Visual Studio Code.

To find out how to install and use the examples provided here, follow the GitHub link. Main positive feature of the interactive notebooks is their readiness to try/use immediately.

About Lambda Expressions

The lambda expression is used for anonymous functions that contain expressions or sequences of operators. All lambda expressions use the lambda operator =>, which can be read as “goes to” or “becomes”. 

The left side of the lambda operator specifies the input parameters, and the right side holds an expression or a code block that works with the entry parameters.

Lambda Logo

Prepare Data for Examples

All the examples provided in this article are done as a single .NET interactive notebook, which you can find at the GitHub link. In order to examine it, you can open it in Visual Studio Code and try it directly without any installation and project creation.

Take note of two code cells in the notebook:

  • The code block to import the necessary libraries:
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
  • And the code block to create data for the provided examples:
class Person
{
  public string FirstName {get; set;}
  public string LastName {get; set;}
  public string Gender {get; set;}

  public string FullName
  {
    get { return FirstName+" "+LastName; }
  }
  
  public int Age {get; set;}
}

var persons = new List<Person>()
{
  new Person()
  {
    FirstName = "John",
    LastName = "Doe",
    Gender = "male",
    Age = 35 
  },
  new Person()
  {
    FirstName = "Ann",
    LastName = "Peterson",
    Gender = "female",
    Age = 30
  }
};

Functions With Lambda Expressions

Delegate with lambda expression:

Func<Person, string> fnGender = (p) => { 
   return p.Gender;
};

Console.WriteLine(
  $"Ann is {fnGender(persons.Where(x=>x.FirstName=="Ann").First())}"
);

And delegate turned into a local function:

string fnGender(Person p)
{
  return p.Gender;
}

Console.WriteLine(
  $"John is {fnGender(persons.Where(x=>x.FirstName=="John").First())}"
);

Actions With Lambda Expressions

In contrast to the Func delegate, an Action delegate may contain only input arguments. When no value is required to be returned from a lambda expression, use the Action delegate type.

Action<Person> PrintPersonDetails = s => Console.WriteLine(
    $"First name: {s.FirstName}, "+ 
    $"Last name: {s.LastName}, " +
    $"Gender: {s.Gender}, " +
    $"Gender: {s.Age}"
  );

PrintPersonDetails(persons[1]);

Some Illustrative Lambda Expression Examples

Task Chain

The example shows the use of lambda expressions in multiple tasks. Take note that the second task is a continuation of the first task.

int i=0;

var task = new Task(() =>
{
  i++;

  Console.WriteLine($"First task {i}");
  Thread.Sleep(2000);
});

Task continuation = task.ContinueWith(t =>
{
  i++;
  Console.WriteLine($"Continue first task 1 {i}");
  Thread.Sleep(2000);
});

task.RunSynchronously();

Lambda with Linq

The example demonstrates the use of the lambda and linq expression combinations.

int minAge = persons.Min(x=>x.Age);
var youngestPerson = persons
                .Where(x => x.Age == minAge)
                .Select(x=>x.FirstName+" "+x.LastName)
                .First();

Console.WriteLine($"Youngest person is {youngestPerson}");

Create Anonymous Type Object List

Create a new object (anonymous type) list with French property names:

var personnes = persons.Select(
  x => new {
    Prénom = x.FirstName,
    NomDeFamille = x.LastName,
    Âge = x.Age,
    LeSexe = x.Gender
  }
);

Console.WriteLine(personnes.ToArray()[0]);

Extract an Array from Object Property Values

The code below shows an example of extracting an array from an object’s property values using a lambda expression.

string[] firstNames = persons
    .Where(x => x.FirstName != null)
    .Select(x => x.FirstName)
    .ToArray();

foreach (var firstName in firstNames) 
  Console.WriteLine($"First name: {firstName}");

Lambda Expression With Iteration

The example demonstrates how to iterate an array using a lambda expression.

persons.ForEach(person =>
{
  Console.WriteLine($"Full name: {person.FullName}");
  Console.WriteLine("");
});

Extract Array with Converted Type

The code below extracts an array from the object property by converting it to another type.

var ages = persons.Select(item => item.Age.ToString()).ToList();

ages.ForEach(age =>
{
  Console.WriteLine($"Age: {age}");
})

Lambda Expression with Delegate

The example demonstrates how to find the maximum of the 3 numbers using lambda expression and delegate.

delegate int max3(int data1,int data2, int data3);

max3 m3 = (x, y ,z) =>  (x > y == true) 
? (x > z == true) 
	? x : z 
: (y> z == true)
    ? y:z;

Console.WriteLine(m3(180,192,354));

Lambda Expressions, Regex and Statistical Functions

The example demonstrates how to calculate a number of sentences in a text, average sentence length (in words), and also the number of substrings contained in the text (‘you’, ‘You’, ‘your’, ‘your’).

string text = @"Don't you wish you could bring your furry best friend with 
you everywhere you go? It just doesn't make sense to take our pets with 
us all the time, and it's so tough to leave them at home. 
Mary asked, How could you do that mom!? You left him ALONE? For 2 HOURS?";

var sentences = text.Split(
  new[] {'.', '!', '?'}, 
  StringSplitOptions.RemoveEmptyEntries);

var regexPattern = new Regex("[Yy]ou[r]*");

double avgLength = sentences.Average(
  x => x.Split(new []{' '}, 
  StringSplitOptions.RemoveEmptyEntries)
  .Length);

int sentenceCount = sentences.Length;

var yous = sentences.Where(
  x => regexPattern.IsMatch(x)).Sum( s1 => regexPattern.Matches(s1).Count);

Console.WriteLine($"Total sentences: {sentenceCount}");
Console.WriteLine($"Average sentence length: {avgLength}");
Console.WriteLine($"Found appealls: {yous}");

Convert Array to Comma-Separated String Using Lambda Expression

The code below converts an array to a string with a comma-separated list.

string[] WorldCities = {  
    "London",
    "New York City",
    "Tokyo",
    "Paris",
    "Singapore",
    "Amsterdam",
    "Berlin",
    "Seoul"
};

// Convert an array to a comma-separated list-string.
var csString = WorldCities.Aggregate((c1, c2) => c1 + ", " + c2);

Console.WriteLine("Comma-separated list: " + csString);

Was this helpful?

2 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *