LINQ Learning (extension method, Delegate, Lambda expression) Article 2

Source: Internet
Author: User
    1. Basic query operator of LINQ-Get Data

(1) The select () syntax is:

Public static ienumerable <tresult> select <tsource, tresult> (

This ienumerbale <tsource> source.

Func <tsource, tresult> selector)

Note: 1) the select method itself is a generic extension method.

2) It acts on the ienumerable <tsource> type

3) Only one func <tsource, tresult> type parameter is accepted.

4) func <tsource, tresult> is a generic deleGATE located in the space of the system name, in system. Core. dll, where selector is an extract.

(2) For example, first define a static class extraclass, and then define a static Extension Method in the static class to implement output information.CodeAs follows:

Public static class extraclass

{

// Provides the output method for ienumerable

Public static void print (this ienumerable <string> IE)

{

Ienumerator <string> result = ie. getenumerator ();

While (result. movenext ())

{

MessageBox. Show (result. Current );

}

}

}

Then, click the button event shown in the figure. The code in the button event is:

 

The code below this event shows the data loops in a generic set. The Code is as follows:

List <string> Persons = new list <string> ();

Persons. Add ("Zhang San ");

Persons. Add ("Zhang San Feng ");

Persons. Add ("Li Si ");

Persons. Add ("Wang Wu ");

Persons. Add ("Wang Liu ");

Persons. Add ("LI Ba ");

Persons. Add ("Lao Wu ");

Persons. Add ("Zhang xx ");

// Output all elements in persons

VaR result = Persons. Select (P => P );

Result. Print ();

The execution result is output cyclically in order.

2. LINQ basic query operator-Data Filtering

(1) The where () syntax is:

Public static ienumerable <tsource> where <tsource> (

This ienumerable <tsource> source,

Func <tsource, bool> predicate)

(1) The where method is a generic extension method.

2) It works the same as select () for ienumerable <tsource> type

3) it only accepts one func <tsource, bool> generic delegate parameter. Here, predicate is a judgment condition.

(2) For example, the above example uses the generic set to output information according to certain conditions. First, create a method to output the information of the person named "Zhang". The Code is as follows:

Public bool judge (string S)

{

If (S. startswith ("Zhang "))

{

Return true;

}

Return false;

}

Under the select control event, use the LINQ code to output a variety of implementation codes that are just surnamed Zhang:

// Output the person with the surname "Zhang" in persons

// Var result = Persons. Where (P => P. startswith ("Zhang"); // method 1

// Var result = Persons. Select (P => P). Where (P => P. startswith ("Zhang"); // method 2

// Var result = Persons. Where (P => P. startswith ("Zhang"). Select (P => P); // method 3

VaR result = Persons. Where (P => judge (p); // Method 4

Result. Print ();

3. Basic query operator-Sort data

(1) The orderby () syntax is:

Pblic static iorderedenumerable <tsource> orderby <tsource, tkey> (

This ienumerable <tsource> Source

Func <tsource, tkey> keyselector)

Note: 1) The orderby method is also a generic extension method.

2) It works the same as select () for ienumerable <tsource> type

3) it only receives one func <tsource, tkey> type parameter. Here, keyselctor specifies the field to be sorted.

4) You can use the orderbydescending method to sort data in descending order.

(2) For example, the Code for sorting is as follows:

// Var result = Persons. orderby (P => P );

// Sort by the last letter of the name

// Var result = Persons. orderby (P => P. substring (P. Length-1, 1). Select (P => P );

// Sort in descending order

VaR result = Persons. orderbydescending (P => P );

Result. Print ();

    1. Basic query operator-grouped data

(1) The groupby () syntax is:

Public static ienumerable <igrouping <tkey, tsource>

Groupby <tsource, tkey> (

This ienumerable <tsource> source,

Func <tsource, tkey> keyselector)

Note: 1) The groupby () method is similar to the orderby () method. It is also a generic extension method.

2) It works the same as orderby () for ienumerable <tsource> type.

3) it only accepts one func <tsource, tkey> type parameter. Here, keyselector specifies the field to be grouped.

(2) For example, the Code for grouping is as follows:

// Group --- group by name -- retrieve the part before the space in the name

VaR result = Persons. groupby (P => P. Split (New char [] {''}) [0]);

Foreach (VAR group in result)

{

Console. writeline ("Last Name:" + group. Key );

Foreach (VAR name in group)

{

Console. writeline ("\ t" + name );

}

Console. writeline ();

}

    1. Query execution time

(1) from the previous test, we found that a query actually goes through the following three steps.

1) Step 1: obtain the data source int [] numbers = new int [] {2,434 };

2) Step 2: Define the query var even = numbers. Where (P => P % 2 = 0). Select (P => {

Console. writeline ("Hi !" + P. tostring ());

Return P ;});

3) Step 3: Execute the query foreach (VAR item in even ){}

    1. Query execution time Section

(1) The query can be divided into the following three steps: getting the data source, defining the query, and executing the query

(2) After a query is defined, the query is actually executed only when enumeration results are required. This method is called "delayed execution ".

(3) When the query result returns a single value, the query is executed immediately. For example, code:

// Query time --- execute the statement immediately when the returned value is a single value, responsible for delayed execution

VaR result = Persons. Select (P => P). Count ();

Console. writeline ("number is" + result );

(4) Therefore, you can use the following techniques to forcibly execute a query when defining a query:

    1. Two Methods for querying by using LINQ

(1) method Syntax: Query Method

The Extension Method and Lambda expression method defined in the system. LINQ. enumerable class are used for query.

(2) query syntax: query statement Method

    1. Query statement vs Query Method

Note: There is a close relationship between Query statements and query methods.

(1) CLR does not understand query statements, but only query methods.

(2) the compiler is responsible for translating query statements into query methods during compilation.

(3) Most query methods have the corresponding query statement format, for example, select () corresponds to select, orderby () corresponds to orderby.

(4) Some query methods currently do not have corresponding query statements in C #: for example, count () and max (). In this case, only the following alternative solutions can be used:

1) Query Method

2) hybrid query statement + Query Method

(5) generally, we recommend that you use a more readable query statement. Example:

You can also use the generic set array persons defined above and query statements to implement several simple functions. The Code is as follows:

// Output all elements in persons

VaR result = from P in persons select P;

// Output the person surnamed Zhang in persons ---- mixed statement and method Orchestration?

VaR result = (from P in persons select P). Where (P => P. startswith ("Zhang "));

// Sort

VaR result = from P in persons orderby P select P;

Result. Print ();

    1. Advanced Query Method

(1) Aggregation class count (), max ()/min (), average (), sum (). Example:

Redefines an array to implement the preceding methods. The Code is as follows:

// Advanced method for querying by using LINQ to objects

// Array data arr

Int [] arr = {23, 34, 5, 5, 23, 45, 65, 33, 43, 76, 67, 87 };

// Aggregation class

Console. writeline ("maximum value of ARR: + arr. Max ());

Console. writeline ("minimum arr values:" + arr. Min ());

Console. writeline ("average arr usage:" + arr. Average ());

Console. writeline ("the array element of ARR is" + arr. Count ());

Console. writeline ("the sum of ARR is:" + arr. sum ());

(2) The sorting class thenby () code is as follows:

// Sorting class

VaR result = arr. orderby (P => P. tostring (). substring (0, 1 ));

// The mixed sorting mode does not meet the requirements.

VaR result = arr. orderby (P => P. tostring (). substring (0, 1). thenby (P => P );

// Sort by statement

VaR T = arr. orderby (P => P. tostring (). substring (0, 1 ));

VaR result = from P in T orderby P descending select P;

(3) The code for taking, takewhile, skip, and skipwhile is as follows:

// Partition class

VaR result = arr. Skip (3). Take (3); // skip three values and take three values.

VaR result = arr. Skip (3); // skip several values

VaR result = arr. skipwhile (P => P> 4); // The method body is a condition that the LINQ statement is not executed in the future. When the condition is set for the first time, all the remaining elements are obtained.

VaR result = arr. takewhile (P => P> 4); // The method body is the condition for the LINQ statement to extract data. When the condition is not true for the first time, the execution is stopped.

(4) The collection class distinct code is as follows:

// Collection class

VaR result = arr. Distinct ();

(5) generate the range class. The repeat code is as follows:

// Generate class ----- static class

VaR result = system. LINQ. enumerable. Range (10, 50 );

VaR result = system. LINQ. enumerable. Range ('A', 50); // generate a continuous sequence

VaR result = system. LINQ. enumerable. Repeat (40, 10 );

Result. Print ();

    1. Summary of generation class query methods

Note: when using the generation class query method, pay attention to the following points:

(1) Unlike other methods, range/repeat is not an extension method, but a common static method.

(2) range can only generate integer sequences.

(3) Repeat can generate generic sequences.

(4) All query methods are stored in the static class system. LINQ. enumerable.

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.