SoFunction
Updated on 2025-03-08

Interpretation of anonymous functions and lambda expressions in C#

C# anonymous functions, lambda expressions, Linq query

1. Use of anonymous functions

Anonymous functions are "inline" statements or expressions that can be used anywhere a delegate type is required.

An anonymous function can be used to initialize a named delegate, or to pass a named delegate (rather than a named delegate type) as a method parameter.

The following example demonstrates the evolution of the delegate creation process from C# 1.0 to C# 3.0:

using System;
using ;
using ;
using ;
using ;

namespace Test0630
{
    delegate void TestDelegate(string s);
    class Program
    {
        static void Main(string[] args)
        {
            // Original delegate syntax required 
            // initialization with a named method.
            TestDelegate testDelA = new TestDelegate(M);

            // C# 2.0: A delegate can be initialized with
            // inline code, called an "anonymous method." This
            // method takes a string as an input parameter.
            TestDelegate testDelB = delegate(string s) { (s); };

            // C# 3.0. A delegate can be initialized with
            // a lambda expression. The lambda also takes a string
            // as an input parameter (x). The type of x is inferred by the compiler.
            TestDelegate testDelC = (x) => { (x); };

            // Invoke the delegates.
            testDelA("Hello,this is TestA");
            testDelB("Hello,this is TestB");
            testDelC("Hello,this is TestC");

            // Keep console window open in debug mode.
            ("Press any key to exit.");
            ();
        }


        static void M(string s)
        {
            (s);
        }
    }
}

2. Lambda expression

The lambda expression is an anonymous function, an efficient expression similar to functional programming. Lambda simplifies the amount of code that needs to be written in development and is the basis of LINQ.

Lambda expression format: (parameter list)=>Expression or statement block, eg the following:

//No sigma() => DoSomeThing() ;

//Single parameterp =>  > 0 ; //Return to Bool
//Multiple parameters( x , y ) => x * y ;

//Input parameters with type( int x , int y ) => x * y;

The following describes the use of Lambda expressions in List collection:

(1) Query all student entities under the class with class number 1001 and return to list1001 to store

var list1001=(t=>==‘1001');

(2) Query all student entities under the class with class number 1001 and return to list1001 to store, and arrange them from small to large according to the student's birth date.

var list1001=(t=>==‘1001').OrderBy(t=>);

Let me talk about it here that OrderBy is sorted from small to large, and OrderByDescending is used if you need to arrange from large to small.

(3) Query all the collections of classmates whose surnames are [Li] under the class number 1001, and arrange them from small to large according to the student's birth date.

var list1001=(t=>==‘1001'&&(“plum”)).OrderBy(t=>);

(4) Query all students with class number 1001 and whose scores are less than 60 in at least one examination subject.

var result = (t => ( == "1001") && ((p =>  < 60 &&  == )));

(5) Other commonly used Lambda expressions are as follows:

var a = (t =&gt;  == "10012");//FirstOrDefault returns the first data that meets the conditions, and returns Null when it does not exist.var b = (t =&gt;  == "Li Shimin");//Return the number of entities that meet the conditionsvar c = (t =&gt; ("middle"));//Find all entities with [medium] in their namesvar d = (t =&gt; );//Group studentList by ClassCodevar f = (t =&gt; );//Return to the maximum date of birth.var e = (t =&gt; );//Sum all resultsvar g = (t =&gt; );//Entertain average scores for all scoresvar h = (t =&gt; ).Distinct();//Get all student names,And remove the duplicate name

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.