Linq
LINQ is an information query statement integrated in a computer language that allows the writer to manipulate the database in a code way.
In C #, LINQ statements are written in two ways.
This is the first form of notation
ienumerable<customer> result = from in customers where " Donna " Select Customer;
Since this is easy to confuse with the SQL language, I prefer to use another way of writing
ienumerable<customer> result = "Donna") = > Customer);
This notation is similar to the syntax of C # statements and is equally easy to understand, so I used this notation when I wrote an ASP.
The LAMDA statement, which is populated with the where and select, is a simplification of the delegate, which facilitates the readability of the code.
The form of the LAMDA expression is usually the case
17
The first student refers to the parameters passed in, = = is the specific symbol of the LAMDA expression, and to the right is an expression, in the query statement, the return value of the expression following this symbol is usually of type Boolean. For example, the above statement in where can filter out students younger than 17 years old.
I've written a simple Web page with a database to test the use of LINQ statements, Web pages using MVC4 templates
This is the model for storing student information
Public classStudent { Public intId {Get;Set; } Public stringName {Get;Set; } Public intAge {Get;Set; } Public intHeight {Get;Set; } }
This context is used to connect to the database
Public class Studentcontext:dbcontext { publicgetset;} }
This is the class used for database initialization
Public classStudentcontextinitializer:dropcreatedatabasealways<studentcontext> { protected Override voidSeed (Studentcontext context) {context. Students.add (NewStudent () {Id =1, Name ="Bob", age = A, Height = the } ); Context. Students.add (NewStudent () {Id =2, Name ="Andy", age =Ten, Height =111 } ); Context. Students.add (NewStudent () {Id =3, Name ="Cooler", age = -, Height =165 } ); Context. Students.add (NewStudent () {Id =4, Name ="Vv", age = -, Height =171 } ); Context. SaveChanges (); } }
Database initialization also requires the following statement in Application_Start ()
Database.setinitializer<studentcontext> (new Studentcontextinitializer ());
This is the LINQ statement test in HomeController
PublicActionResult Index () {Studentcontext db=NewStudentcontext (); varStudents = db. Students.where (Student = Student.age < the). ToList (); Viewbag.message="\ n"; foreach(varStudentinchstudents) {Viewbag.message+=student. Name; Viewbag.message+="\ n"; } returnView (); }
Output (template lazy change to see it)
C # Learning Record (vii) LINQ statements and LAMDA expressions