Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Invoke the Lambda Expression

As you have seen in the previous section, the lambda expression is a shorter way of representing an anonymous method. An anonymous method can be created using delegate, which can be invoked in the same way as a function. So, a lambda expression can be assigned to a compatible delegate type and be invoked like a delegate.

Consider the following lambda expression that determines whether a student is a teenager or not.

Example: Lambda expression C#
s => s.age > 12 && s.age < 20;
Try it

To invoke the above lambda expression, first of all create a delegate that accepts a paramter of Student type, returns a boolean value and then assigns the lambda expression, shown above, to the delegate type as shown below. Then the delegate type variable with () operator must be used to invoke it.

Example: Invoke lambda expression in C#
delegate bool isTeenAger(Student student);

isTeenAger isStudentTeen = s => s.age > 12 && s.age < 20;

Student std = new Student() { age = 21 };

isStudentTeen(std);// returns false

Instead of creating a custom delegate type (isTeenAger) as shown above, you can use built-in delegate types Func<> and Action<>.

Func Delegate type

Use the Func<> delegate when you want to return something from a lambda expression. The last parameter type in a Func<> delegate is the return type and rest are input parameters. Visit Func delegate section of C# tutorials to know more about it.

Consider the following lambda expression to find out whether a student is a teenager or not.

Example: Lambda expression assigned to Func delegate in C#
Func<Student, bool> isStudentTeenAger = s => s.age &gt; 12 && s.age &lt; 20;

Student std = new Student() { age = 21 };

bool isTeen = isStudentTeenAger(std);// returns false

In the above example, the Func delegate expects the first input parameter to be of Student type and the return type to be boolean. The lambda expression s => s.age > 12 && s.age < 20 satisfies the Func<Student, bool> delegate requirement, as shown below:

Func delegate with Lambda Expression

The Func<> delegate shown above, would turn out to be a function as shown below.

Example: Func delegate in C#
bool isStudentTeenAger(Student s)
{
    return s.Age &gt; 12 && s.Age &lt; 20;
}

Action delegate type

Unlike the Func delegate, an Action delegate can only have input parameters. Use the Action delegate type when you don't need to return any value from lambda expression.

Example: Lamda expression assigned to Action delegate in C#
Action<Student> PrintStudentDetail = s => Console.WriteLine("Name: {0}, Age: {1} ", s.StudentName, s.Age);

<span className="userclass">Student</span> std = <span className="kwrd">new</span> <span className="userclass">Student</span>(){ StudentName = <span className="str">"Bill"</span>, Age=21};

PrintStudentDetail(std);

You can pass a lambda expression of Func or Action delegate type to a LINQ query. Enumerable static class for LINQ includes Where extension method for IEnumerable<T> that accepts a predicate of Func<TSource,bool>. So, the Where() extension method for IEnumerable<Student> collection is required to pass Func<Student,bool>, as shown below:

Func delegate parameter in Where extension method

So now, you can pass the lambda expression assigned to the Func delegate to the Where() extension method in the method syntax as shown below:

Example: Func delegate in LINQ Method Syntax
IList<Student> studentList = new List<Student>(){...};

<span className="userclass">Func</span>&lt;<span className="userclass">Student</span>, <span className="kwrd">bool</span>&gt; isStudentTeenAger = s => s.age &gt; 12 && s.age &lt; 20;

var teenStudents = studentList.Where(isStudentTeenAger).ToList<Student>();
Example: Func delegate in LINQ Query Syntax
IList<Student> studentList = new List<Student>(){...};

Func<Student, bool> isStudentTeenAger = s => s.age &gt; 12 && s.age &lt; 20;

var teenStudents = from s in studentList
                   where isStudentTeenAger(s)
                   select s;

You can follow the same method in VB.Net to pass Func delegate.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.