Recently in the learning of some of the basics of LINQ, read C # Advanced programming and read a few excellent inside the garden blog, some experience, feel should be recorded, as a review to use. Are some of the most basic knowledge, broadly divided into three parts: LINQ pre-knowledge; LINQ query; LINQ to SQL. Novice can see, Daniel can point pointing, thank you.
First, LINQ preparation Knowledge:
1. Implicit type
Before an implicit type occurs, the practice is to
int Ten ; string " ABC ";
Using an implicit type, the code is as follows:
var Ten ; var " ABC ";
Don't worry about using VAR to affect its performance, because Int and var translate into intermediate languages.
2. Anonymous type
var New 2 " Tom " }; Console.WriteLine (obj.name);
In the code above, anonymous defines a type and constructs the object obj, after which you can call its properties directly without worrying about any other problems.
3. Automatic attributes
Previously, you defined a property for a class:
Private string name; Public string Name { getreturn name;} Set {name = value;} }
c#3.0 using Auto-implemented properties:
Public string Get set; }
4. Extension method
There are a lot of times when you need to do something about the CLR type, and you can't extend the CLR type method, you can create only one helper method or subclass, and the extension method makes these requirements possible. The concrete examples are as follows:
// non-nested, non-generic static classes Public Static class Entendmethod { // static method, at least one parameter, first parameter must append this as prefix, first parameter cannot have other modifiers Public Static void Printstring ( this String val) { Console.WriteLine (val); } }
To call an extension method:
var " AAA " ; str. Printstring (); // Calling extension methods
5. Object initializer
Very simple, see specific examples can understand, the code is as follows:
Public classStudent { Public intID {Get;Set; } Public stringName {Get;Set; } Public intAge {Get;Set; } }//using the object initializer methodlist<student> students =NewList<student>(); Students. ADD (NewStudent {ID =1, Name ="Tom", age = + }); Students. ADD (NewStudent {ID =2, Name ="Tom2", age = A }); Students. ADD (NewStudent {ID =3, Name ="Tom3", age = at});
6. Set initializer
Also use the Student class above:
//using the set initializer methodList<student> students2 =NewList<student> { NewStudent {ID =1, Name ="Tom", age = +}, NewStudent {ID =2, Name ="Tom2", age = A}, NewStudent {ID =3, Name ="Tom3", age = at} };
7, some other simple basic knowledge:
Delegates, generic delegates, anonymous methods, lambda expressions, see Delegate Learning notes Follow-up: Generic delegates and anonymous methods involved in delegates, lambda expressions
Second, LINQ query
1. Basic Inquiry
Use the set students above for a simple query:
// Simple Query var from inch Students where a Select s; foreach (var in studentselect) { ":" + s.age); }
2. Generate a new Type Object
//Building new Objects varItems = fromSinchStudents Select New{Bianhao=s.id, Nianlian=S.age}; foreach(varIteminchitems) {Console.WriteLine (Item.bianhao+":"+Item.nianlian); }
3. Use where filter to query
An instance can continue with an instance of the above (2):
varItems = fromSinchStudentswhereS.id >1 Select New{Bianhao=s.id, Nianlian=S.age}; foreach(varIteminchitems) {Console.WriteLine (Item.bianhao+":"+Item.nianlian); }
4. Using index filtering
However, there are times when you cannot use LINQ queries, which are not available when handling overloads of the Where () method, which is done with index, with the following code:
var items2 = students 520); foreach (var in items2) { "" + item. Name); }
5. Type Screening
object [] objs = { " a , 2 , 4 , b , 9 , " d " var item3 = Objs. Oftype<int > (); foreach (var item in Item3) {Console.WriteLine (item); }
6, compound FROM clause
LINQ can be applied at query time using the FROM clause
7. Sorting
By s.id Descending, the concrete examples are as follows:
var items4 = from s in students wher E s.age > 22 o Rderby s.id descending select S; foreach (var s in Items4) {Console.WriteLine (s.name + " : " +
var items5 = students. (r = r.age); // Ascending var items6 = students. OrderByDescending (r = r.age); // Descending foreach (var in items5) { ":" + s.age); }
8. Aggregation operator
Count (), Sum Min Max Average Aggregate does not return a sequence and returns a value. Examples are as follows:
int[] Nums =New int[] {1,2,3,5, A, -, at }; varnum = fromNinchNumsSelectN; intresult =Num. Sum (); Console.WriteLine (result); varITEMS7 = fromSinchStudentsSelects; varItemvalue = Items7. Max (M =m.age); Console.WriteLine (itemvalue);
Third, LINQ to SQL
The LINQ to SQL has never been clear about what is going on, the understanding of its own records, and later if there is a deeper understanding when the correction.
Open Server Explorer and add the following data tables. As follows:
A simple explanation: The database table guest is the guest's ID, name, age, Room ID (r_id of the rooms table), with ID, name, and price.
Check the name and price of room with room price greater than 28:
Public voidSelectroom () {Hoteldatacontext db=NewHoteldatacontext (); varRooms = fromRinchdb. thewhereR.r_price > - SelectR; foreach(varRinchrooms) {Console.WriteLine ("Roomname:"+ R.r_name +"Price :"+R.r_price); } }
Query: Query the guest's name, age, room name, price, the code is as follows:
Public voidSelectguestroominfo () {Hoteldatacontext db=NewHoteldatacontext (); varGuestinfo = fromGinchdb. Guest Join Rinchdb. G.g_roomid equals r.r_idSelect New{Name=G.g_name, age=G.g_age, Roomname=R.r_name, Price=R.r_price,}; foreach(varGinchguestinfo) {Console.WriteLine ("Name:"+ G.name +"Age :"+ G.age +"Roomname:"+ G.roomname +"Price :"+G.price); } }
At the end of the day, if you have an in-depth understanding, you can change the Add.
LINQ Learning Notes