The Lambda expression in C3.0 is explained in detail

  • 2020-05-19 05:37:28
  • OfStack

In C # 2.0, Microsoft has introduced some new features such as generics, anonymous delegates, and so on. However, these new features give the impression that they are more or less "copied" from other languages (e.g., generics are like C++ templates, and some features are like 1 in Java). But in C # 3.0, Microsoft brought me some new features that probably none of the development languages had before. This undoubtedly demonstrates the powerful advantages of C#3.0 in developing languages.

Lambda expression

An Lambda expression is an anonymous function that can contain expressions and statements and can be used to create a delegate or expression directory tree type. All Lambda expressions use the Lambda operator = > . For a more detailed explanation of Lambda, see MSDN. It makes it very clear.

Here is a simple example to illustrate the benefits of Lambda. Lambda provides a clearer implementation of the handling of anonymous delegates. For example, in 2.0. We can write code like this:


publicclassExample 
{ 
publicstaticvoidDemo(System.Windows.Controls.TextBlockoutputBlock) 
{ 
Funcconvert=delegate(strings) 
{returns.ToUpper();}; 

stringname="Dakota"; 
outputBlock.Text+=convert(name)+"n"; 
} 
}

Func in C# < (Of < (T, TResult > ) > ) delegate with anonymous method 1.

In 3.0, we can use Lambda to transfer parameters more clearly:


publicclassExample 
{ 
publicstaticvoidDemo(System.Windows.Controls.TextBlockoutputBlock) 
{ 
Funcconvert=s=>s.ToUpper(); 

stringname="Dakota"; 
outputBlock.Text+=convert(name)+"n"; 
} 
}

The base type of the Lambda expression is the generic Func delegate 1. This allows you to pass an lambda expression as a parameter without explicitly assigning it to a delegate. In particular, because many type methods in the System.Linq namespace have Func < (Of < (T, TResult > ) > ), so you can pass lambda expressions to these methods without explicitly instantiating Func < (Of < (T, TResult > ) > ) delegation. This makes our code simpler and logically easier to understand.

Object initialization

In C#, object initialization has also been improved. A new feature is the provision of more convenient syntax rules for declaring variable values.

Suppose we declare an Student object:


publicclassStudent 
{ 
privatestring_stuName; 
privatestring_stuAge; 
privateint_stuClass; 

publicStudent(){} 

publicstringStuName 
{ 
get{return_stuName;} 
set{_stuName=value;} 
} 

publicstringStuAge 
{ 
get{return_stuAge;} 
set{_stuAge=value;} 
} 

publicintStuClass 
{ 
get{return_stuClass;} 
set{_stuClass=value;} 
} 

}

In C#2.0, we declare variables and assign values like this:


Studentstu=newStudent(); 
stu.StuName="Brian"; 
stu.StuAge="21"; 
stu.StuClass="1 class ";

In C#3.0, we can initialize objects by:


Studentstu2=newStudent 
{ 
StuName="Brian", 
StuAge="21", 
StuClass="1 class " 
};

As you can see from the code, C#3.0 gives you a convenient way to initialize objects.

The query

You should have heard about this, that is the famous Linq. This is one of the most unique and useful new features in C#3.0. Linq has changed the way we write data applications. Previously, developers needed to think about and write different code to process data from different data sources (SQL Server, XML, Memory...). . LINQ is a good solution to this annoying problem. Meanwhile, with the help of Lambda, we can more conveniently and accurately query the data we want.

Simple data query example using Linq:


privatevoidBindGridView(stringcriteria) 
{ 
stringstrConn=ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; 
NorthwindDbdb=newNorthwindDb(strConn); 

IEnumerableresults; 

if(criteria==string.Empty) 
{ 
results=db.Employee.ToArray(); 
} 
else 
{ 
results=(fromcindb.Employee 
wherec.FirstName.Contains(criteria) 
selectc).ToArray(); 

} 
GridView1.DataSource=results; 
GridView1.DataBind(); 
}

Variable declarations

This is var. var is a keyword provided in C#3.0 for declaring variables, and developers can declare variables regardless of their type (this 1 usage is very similar to Javascript). But there are some differences.

Similarities: declare any type of local variable with var.

Difference: it's only responsible for telling the compiler that the variable needs to be inferred from the initialization expression about the type of the variable, and that it can only be a local variable.

We can declare variables like this:


vari=10; 
varname="edisundong"; 
varnumbers=newint[]{1,2,3};

var is just a keyword, it's not a new type in C#3.0, but it's responsible for telling the compiler that the variable needs to infer the type of the variable based on the initialization expression, and the statement above is equivalent to


inti=10; 
stringname="edisundong"; 
int[]numbers=newint[]{1,2,3};

Here are a few things to note:

1. Must be assigned at the same time as the declaration.

2. After declaring a local variable with var, it is still strongly typed.

varinteger=10;
integer="edisundong";

Compile time reports Cannot implicitly convert type string to int error.

3. The compile-time type of the initializer expression cannot be null (null).
4. The declaration of var is limited to local variables

Extension methods

Previously, if we wanted to extend the functionality of a class, we had to derive it directly from and learn from its methods. In C#3.0, we introduced a quick way to extend functionality.


publicstaticclassStudentExtensionMethods 
{ 
publicStudentExtensionMethods() 
{ 
// 
//TODO: Add the constructor logic here  
// 
} 
publicstaticstringGetStudentInformation(thisStudentstu) 
{ 
returnstring.Format("Name:{0}{1}Age:{2}",stu.StuName, 
stu.StuAge,stu.StuClass); 
} 
}

Define 1 class, where define 1 method, note: this class and method are static, and the method parameter is Student. In this way, the Student class extends the GetStudentInformation method:


Studentstu2=newStudent 
{ 
StuName="Brian", 
StuAge="12", 
StuClass="1 class " 
}; 
Console.WriteLine(stu2.GetPersonInformation());

Summary: after learning C#3.0 for the first time, I felt that it brought many surprises, including many new features that were previously unknown. The new features of C#3.0 should go beyond that.


Related articles: