Recommendation 27: Use a lambda expression in a query
LINQ is actually based on extension methods and lambda expressions. Any LINQ query can be replaced by the way it is extended.
var from inch personlist Select New {personname = person. Name, CompanyName = person.companyid==0? " Micro ":"Sun" }; foreach (var in personwithcompanylist) { Console.WriteLine (item. ToString ());}
Equivalent to:
foreach (var in Personlist.select (person=>new {Personname=person). Name,companyname=person. companyid==0? " Micro ":"Sun"})) { Console.WriteLine (item. ToString ());}
Most extension methods for LINQ design have generic delegates applied. The System namespace defines the generic delegate action, Func, and predicate. The action is used to perform an operation, so it does not return a value; Func is used to perform an operation and return a value; predicate is used to define a set of conditions and to interpret whether the parameters meet the criteria. The Select extension method accepts a Func delegate, and the lambda expression is a concise delegate, and the operator "= =" On the left represents the parameter of the method, and the method body on the right.
We use lambda expressions by calling extension methods directly, which completes the functionality and reduces the line of code. In practical work, this method should be used flexibly.
foreach (var in Personwithcompanylist.where (p=>p.companyname=="Sun") { Console.WriteLine (item). personname);}
Output:
Mike
Steve
Call the OrderByDescending extension method, sorting for PersonName:
foreach (var in personlist.orderbydescending (person=>). Name) { Console.WriteLine (item). Name);}
Output:
Steve
Rose
Mike
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 27: Using lambda expressions in queries