LINQ & EF for US (2)-LINQ to object)

Source: Internet
Author: User
Tags element groups

(Original: ash insects home http://hi.baidu.com/grayworm)
LINQ to objects is the core of the LINQ family. Other LINQ also use the same query syntax as that of LINQ to objects.In the end, the compiler translates the LINQ syntax into a chained expression of the extension method, converts the lambda expression in the extension method into an anonymous method in the anonymous class, and then compiles the query expression into msil.
Instead of converting a query expression to msil, you can convert the query expression tree to a specific query language. LINQ to SQL generates T-SQL, LINQ to entities generates esql, and LINQ to XML generates XPath statements.

List of standard query operators in LINQ



Figure 1

The following is an example of how to query data in vs2008 and later.Program.
\ Programe files \ Microsoft Visual Studio 2008 (10.0 vs2010) \ samples \ 1033a compressed package csharpsamples.zip under the folder, decompress it, and continue to open the folder.
. \ Linqsamples \ samplequeries. sln. Open this solution and run the project. The interface is as follows:



Figure 2
Select an example on the left, and the corresponding LINQCode, The code running result is displayed at the bottom of the right side. Through this sample program, we can learn various usage of LINQ.

Next, let's learn the common operators of LINQ.
I. filter operator where
Filter the content of the source Sequence Based on the predicate, similar to the WHERE clause in SQL.

1. Simple where expression
Use extension methods
VaR query1 = customerlist. Where (C => C. Country = "USA ");
Use the query expression syntax
Query1 = from C in customerlistWhere C. Country = "USA" select C;
To use the extension method, you must input a Lambda expression to the where method.

2. compound where expression
The compound where expression isUse the & or | Operator to filter data
Use extension methods
VaR query2 = customerlist.Where (C => C. Country = "USA" & C. Orders. Any ());
Use the query expression syntax
Query2 = from C in customerlistWhere C. Country = "USA" & C. Orders. Any () Select C;

The any () method is equivalent to count ()> 0. If the set contains elements, true is returned.

3. Use the index parameter and the indexof () method
The index value indicates the index number of the element in the set. You can use index in where () to control the collection data related to the specified index number.
Indexes can be used for query operations that return the ienumerable <t> type.
Use extension methods
VaR query3 = customerlist. Where (C, index) => C. Country = "USA" & index> 70 );// A collection of elements whose return country is USA and whose index number is greater than 70.
Here, the lambda expression receives the (C, index) parameter, and the index number is passed as the second parameter.

You can also use the indexof () method to implement the above functions.If indexof () is used, only one parameter is required in the lambda expression.
Use extension methods
VaR query3 = customerlist.Where (C => C. Country = "USA" & customerlist. indexof (c)> 70 );
Use the query expression syntax
Query3 = from Cust in customerlistWhere Cust. Country = "USA" & customerlist. indexof (Cust)> 70Select Cust;

Ii. projection operators

Projection Operator corresponds to the "Select column name" clause in SQL

(1) Select
The select operator returns a set of specified attributes from the sequence source.
Use extension methods
VaR Infos = context. Infos. Where (P => P. Sex = true). Select (P => New {P. Name, P. Sex });
Foreach (var c in Infos)
{
Console. writeline (C. Name + C. Sex );
}
Use the query expression syntax
VaR Infos = from P in context. Infos where P. Sex = trueSelect New {P. Name, P. Sex };
Foreach (var c in Infos)
{
Console. writeline (C. Name + C. Sex );
}
If you use the extension method, use the lambda Expression P => New {P. name, P. sex} to project the column. If the query expression syntax is used, the anonymous class new {P. name, P. sex.

(2) selectworkflow
The selectmany operator actually implements cross-Join Operations on relevant data. It returns the specified attribute from a one-to-multiple sequence based on the lambda expression.
For example:



Figure 3
Query all family members of a male employee:
Use extension methods
VaR q = context. Infos. Where (P => P. Sex = true ).Selectnames (F => F. families );
Foreach (var n in Q)
{
Console. writeline (N. Name );
}
Use the query expression syntax
VaR q = from P in context. Infos where P. Sex = trueFrom F in P. Families select F;
Foreach (var n in Q)
{
Console. writeline (N. Name );
}

Iii. Block Operators
(1) Skip and take
Skip is the number of elements skipped from the sequence; take is the number of elements obtained from the sequence;
For example, skip the first two elements of the set and take four elements from the third element.
Use extension methods
VaR q = List.Skip (2). Take (4 );
Use the query expression syntax
VaR q = (from P in list select P ).Skip (2). Take (4 );

(2) skipwhile and takewhile
Skipwhile: the condition is skipped. It is determined from the first element of the sequence and jumped until the element that does not meet the condition is exceeded. This element and the sequence after this element are returned;
Takewhile: Condition capture, which starts from the first element of the sequence and determines in sequence. If the conditions are met, the next element is judged until the elements that do not meet the conditions are returned;
For example, the first batch of "gender" in the set is the set of "male" elements.
Use extension methods
VaR q = List.Skipwhile (P => P. Sex = false). takewhile (P => P. Sex = true );
Use the query expression syntax
VaR q = (from P in list select P ).Skipwhile (P => P. Sex = false). takewhile (P => P. Sex = true );

Iv. Join Operators
The join and groupjoin operators associate two mutually independent objects through key attributes.The association between such objects is somewhat different from the join Association syntax in SQL.
1. The join of LINQ does not support some comparison operators in the SQL-92, such as >,<, <>. It only supports equal Operators
2. In the on clause, = cannot be used to associate two objects. The equals operator is required.
(1) join

Use extension methods
VaR list = Infos.Join (works, P => P. code, W => W. infocode, (p, W) => New {P. name, W. firm, W. depart });
Use the query expression syntax
VaR list = from P in InfosJoin W in works on p. Code equals W. infocodeSelect New {P. Name, W. Firm, W. Depart };
(2) groupjoin
Achieving external effects

The join extension method and the groupjoin extension method have different signatures.



Figure 4



Figure 5
In C #3.0Query expression syntaxNo groupjoin syntax,You can use join... into... to implementIt is different from join, which can achieve the effect similar to that of SQL Outer Join, while join only achieves the effect similar to that of SQL inline.
Use the query expression syntax
VaR list = from P in InfosJoinW in works on p. Code equals W. infocodeInto BoFrom R in Bo. defaultifempty () Select New {P. Name, r };

5. Join Operators
The Concat operator is used to connect two sequences to one sequence. It is similar to the relationship in SQL or the OR operator.
Use extension methods

VaR q = Infos. Select (P => P. Name ).Concat (works. Select (W => W. Firm ));
Use the query expression syntax
VaR q = (from P in Infos select P. Name ).Concat (from W in works select W. Firm );

Vi. Sorting Operators
The sorting operators include five operators: orderby, orderbydescending, thenby, thenbydescending, and reverse.
Orderby: Sort in ascending order
Orderbydescending: Sort in descending order
Thenby: Implement incremental sorting after orderby or orderbydescending.
Thenbydescending: Implement descending sorting in multi-level sorting after orderby or orderbydescending
Reverse: Reverse Order

For example, all employees are sorted by gender in ascending order and then by birthday in descending order.
Extension Method:
VaR q = Infos.Orderby (P => P. Sex). thenbydescending (P => P. Birthday );
Use the query expression syntax:
VaR q = from P in InfosOrderby P. Sex, P. Birthday descending select P;
Multi-level sorting in the query expression syntax is similar to that in T-SQL.

VII. grouping operators
The Group operator groupby is used to group elements in a sequence based on an attribute of an element.Similar to the group by clause in SQL, but it is a sequence of objects, and each element object in each group can be obtained.
For example, group Employees by Gender and display the information of the employees in each group.
Extension Method:
VaR q = Infos.Groupby (P => P. Sex );;
Use the query expression syntax:
VaR q = from m in InfosGroup M by M. Sex into GSelect g;
Show group data:
Foreach (VAR item in Q)
{
// Item. Key indicates the value of the keyword After grouping. Here it is the value of gender sex.
Console. writeline ("Gender:" +Item. Key+ "\ T total" +Item. Count ()+ "Persons ");
Foreach (VaR C in item)
{
Console. writeline ("\ t" +C. Name+ "\ T" +C. Sex);
}
Console. writeline ("*********************");
}



Figure 6

8. Set Operators
The Set operators include distinct, union, intersect, and distinct T. Except distinct, the other three operators are used to combine the two sets into a set.
(1) distinct
The distinct operator is used to remove repeated values from the sequence, similar to the distinct operator in SQL.
For example, view all
Extension Method:
VaR q = Infos. Select (P => P. Nation ).Distinct ();
Use the query expression syntax:
VaR q = (from P in Infos select P. Nation ).Distinct ();

(2) Union
The Union operator obtains the union of two sets with the same structure. If the two sets have the same elements, the duplicate content is automatically filtered out. The Concat operator mentioned above only merges two sets and does not filter repeated elements.
For example, temp is a subset of Infos.
VaR Infos = from P in context. Infos. tolist () select P;
VaR temp = Infos. Where (P => P. Sex = true );
Extension Method:
VaR q = Infos.Union (temp );
Use the query expression syntax:
VaR q = (from P in Infos select P ).Union (from m in temp select m );
In the running result, the content of the subset is not repeated.

(3) intersect
The Intersect operator is the intersection of two sets with the same structure.
For example, temp is a subset of Infos.
VaR Infos = from P in context. Infos. tolist () select P;
VaR temp = Infos. Where (P => P. Sex = true );
Extension Method:
VaR q = Infos. Intersect (temp );
Use the query expression syntax:
VaR q = (from P in Infos select P ).Intersect (from m in temp select m );
Only the content in the subset is displayed in the running result.

(4) memory T
The distinct t operator is used to retrieve the difference set of another set from one set, that is, to retrieve elements not included in Set B from set.
For example, the Infos and temp Collections contain elements that do not exist in the Infos collection.
VaR Infos = from P in context. Infos. tolist () select P;
VaR temp = Infos. Where (P => P. Sex = true). tolist ();
Temp. Add (new info
{
Code = "P100 ",
Name = "Haha ",
Sex = false,
Nation = "n004 ",
Birthday = datetime. Now
});
Extension Method:
VaR q = Infos.Using T (temp );
Use the query expression syntax:
VaR q = (from P in Infos select P ).Distinct T (from m in temp select m );

9. Conversion operator used to change the type of a set
(1) toarray

Converts a set to an array without delay
Extension Method:

Info [] G= Infos.Toarray ();
Use the query expression syntax:
Info [] G= (From P in Infos select P ).Toarray ();
(2) tolist
Converts a set to a generic set without delay
Extension Method:
List <info> G= Infos. Tolist ();
Use the query expression syntax:
List <info> G= (From P in Infos select P ).Tolist ();

(3) todictionary
Converts a set to a set of the dictionary <tkey, telement> type. The value of each element is an element object in the original set.
For example, the following code converts the content of a set into a dictionary set. The dictionary key value is the personnel code, and the dictionary value is the info Element Object.

Extension Method:
VaR q = Infos. Todictionary (P => P. Code );
Use the query expression syntax:
VaR q = (from P in Infos select P ).Todictionary (P => P. Code );
Call syntax
Foreach (VaR item in Q)
{
Console. writeline (Item. Key + item. value. Name);
}
From the running results, we can see that the second parameter of the dictionary is the element in the original set.

(4) tolookup
Converts a set to an ILookup <tkey, telement> type set,The differences between the ILookup <tkey, telement> set and the dictionary <tkey, telement> set are: keys and values in the dictionary <tkey, telement> match one by one, while the ILookup <tkey, telement> the key and value values in the set are one-to-many mappings.
For example, use ILookup <tkey, telement> to display element groups in the set.
Extension Method:
VaR q = Infos. tolookup (P => P. Nation );
Use the query expression syntax:
VaR q = (from P in Infos select P). tolookup (P => P. Nation );
Code for displaying data:
Foreach (VAR item in Q)
{
Console. writeline (item. Key );
Foreach (VaR single in item)
{
Console. writeline ("\ t" + single. Name );
}
}
Display Effect:



Figure 7
(Original: ash insects home http://hi.baidu.com/grayworm)

10. Equality OPERATOR: sequenceequal
Compares two sequences.If the values of all elements are equal, the number of elements is equal, and the order of the elements is equal, the sequenceequal operator returns true; otherwise, false.
VaR S1 = Infos. orderby (P => P. Code );
VaR S2 = Infos. orderbydescending (P => P. Code );
VaR S3 = Infos. orderby (P => P. Code );
Console. writeline (s1.sequenceequal (S2); // The result is false.
Console. writeline (s1.sequenceequal (S3); // The result is true.

11. Element operators:
The element operator returns a specified element from the ienumerable <t> set sequence.
If the specified element is not found, all xxxdefault operators return NULL objects without any exception. The first, last, single, and elementat operators can produce exceptions.

(1) first and firstordefault
If the sequence contains one or more elements, the two operators return the first element in the sequence. If the sequence does not contain any element, the firstordefault operator returns a null value (reference type) or a default value (value type), while the first operator generates an exception.
For example, find the first girl
Extension Method:
VaR item = Infos. First (P => P. Sex = false );
VaR item = Infos. Where (P => P. Sex = false ).First ();
Use the query expression syntax:
VaR item = (from P in Infos where P. Sex = false select P ).First ();

(2) Last and lastordefault
If the sequence contains one or more elements, the two operators return the last element of the sequence. If the sequence does not contain any element, the lastordefault operator returns a null value (reference type) or a default value (value type), and the last operator generates an exception.
For example, find the last girl.
Extension Method:
VaR item = Infos. Last (P => P. Sex = false );
VaR item = Infos.Where (P => P. Sex = false). Last ();
Use the query expression syntax:
VaR item = (from P in Infos where P. Sex = false select P ).Last ();

(3) single and singleordefault
If there is only one element in the sequence, the two operators return this element.
If there is no element in the sequence, single will produce an exception, while singleordefault will return a null value (reference type) or default value (value type)
If the sequence contains multiple elements, both operators will generate exceptions.

(4) elementat and elementatordefault
The two operators return the specified element from the sequence based on the index number. If the element elementat () is not found, an exception occurs, and elementatordefault () returns the default instance.
For example, remove the second girl from the set.
Extension Method:

VaR item = Infos. Where (P => P. Sex = false ).Elementat (2 );
Use the query expression syntax:
VaR item = (from P in Infos where P. Sex = false select P ).Elementat (2 );

12. element quantity Operator
Determine whether the elements in the sequence meet the specified conditions and return the bool value. If this operator is used, the statement cannot be executed in a delayed query.
(1) Any
Returns true if any element in the sequence meets the conditions.
For example, determine whether a person code p005 exists.
Extension Method:
VaR q = Infos.Any (P => P. Code = "p005 ");
VaR q = Infos.Where (P => P. Code = "p005"). Any ();
Use the query expression syntax:
VaR q = (from P in Infos where P. Code = "p005 ").Any ();

(2) All
Returns true if all elements in the sequence meet the conditions.
For example, judge whether all employees are Han Nationality
Extension Method:
VaR q = Infos.All (P => P. Nation = "Han ");
Use the query expression syntax:
VaR q = (from P in Infos select P ).All (P => P. Nation = "Han ");

(3) contains
Determines whether the set contains the specified element.

13. Aggregate Operators
An aggregate operator is similar to an aggregate function in an SQL statement. All LINQ statements with an aggregate operator have no delay function and are immediately executed.

(1) count

Obtains the number of elements that meet the conditions in a sequence.
Extension Method:

VaR q = Infos.Count (P => P. Sex = false );
VaR q = Infos.Where (P => P. Sex = false). Count ();
Use the query expression syntax:
VaR q = (from P in Infos where P. Sex = false select P ).Count ();

(2) min, Max, sum, and average

Obtain the minimum value, maximum value, sum, and average value of an attribute of all elements in the sequence.
Decimal? Minfreightcharge = orderlist.Min(C => C. Freight );
Decimal? Maxfreightcharge = orderlist.Max(C => C. Freight );
Decimal? Sumfreightcharge = orderlist.Sum(C => C. Freight );
Decimal? Avgfreightcharge = orderlist.Average(C => C. Freight );

Summary:
This articleArticleThis section describes the standard query operators (sqo) of LINQ ). We have introduced the use of extension methods and the use of Query expressions for each operator. You should master these two methods, especially remember the use of extension methods.
The running results of each example are not captured due to time. You can test the results on your own.
The above content is the basic syntax of LINQ to object and also the basis of other LINQ. The Skillful Use of these operators allows us to freely ride in the LINQ world.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.