[Reading Notes] C # chapter 6 of Advanced Programming,

Source: Internet
Author: User

[Reading Notes] C # chapter 6 of Advanced Programming,

(1) LINQ Overview

Language Integrated Query (LINQ) inherits the Query syntax in C # programming Language and can access different data sources with the same syntax.

 

1. LINQ Query

var query = from r in Formula1.GetChampions()            where r.Country == "Brazil"            orderby r.Wins descending            select r;

This is a LINQ query. clauses from, where, orderby, descending, and select are pre-defined keywords in this query.

 

2. Expansion Method

The extension method is declared in the static class and defines a static method. The first parameter defines the extension type.

Example:

public static void WriteWithTime(this string message){    Console.WriteLine(message + "," + DateTime.Now.ToString("yyyy-MM-dd"));}

To distinguish it from a general static method, the extension method also needs to use the this keyword for the first parameter.

Now you can use the WriteWithTime () method with the string type.

Example:

string message = "test txt";message.WriteWithTime();

One class that defines the LINQ extension method is Enumerable in the System. Linq namespace.

Example:

List<int> intList = new List<int>() { 1, 2, 3, 4, 5 };var maxIntList = intList.Where(i => i > 4);

Use the Where extension method to obtain a value greater than 4.

 

3. Deferred query execution

When a query expression is defined during running, the query will not run. Query is performed when data items are iterated.

Example:

List<int> intList = new List<int>() { 1, 2, 3, 4, 5 };var maxIntList = intList.Where(i => i > 4);foreach (var item in maxIntList){    Console.WriteLine(item);}intList.Add(6);foreach (var item in maxIntList){    Console.WriteLine(item);}

Run the above Code and the result is as follows:

 

Note that the extension method is called every time a query is used in an iteration (changes in the data source can be detected ). However, calling the extension methods ToArray () and ToList () can change this operation.

Example:

List <int> intList = new List <int> () {1, 2, 3, 4, 5}; var maxIntList = intList. where (I => I> 4 ). toList (); // call the ToList () method foreach (var item in maxIntList) {Console. writeLine (item);} intList. add (6); foreach (var item in maxIntList) {Console. writeLine (item );}

Run the above Code and the result is as follows:

 

 

 

(2) standard query Operators

Reference: http://www.cnblogs.com/heyuquan/p/Linq-to-Objects.html

 

(3) Parallel LINQ

1. Parallel Query

Example:

var data = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };var res = data.AsParallel().Where(d => d > 2);

Call the AsParaller () method to perform the parallel query of LINQ.

 

2. Partition Machine

The AsParallel () method not only extends the IEnumerable <T> interface, but also extends the Partitioner class of the System. Collection. Concurrent namespace.

Example

var data = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };var result = Partitioner.Create(data, true).AsParallel().Where(d => d > 2);

Use the Create () method to manually Create a partition.

 

3. Cancel

. NET provides a standard way to cancel tasks that run for a long time, which is also applicable to parallel LINQ.

Example:

Var data = new List <int> () {1, 2, 3, 4, 5, 6, 7, 8}; var cts = new CancellationTokenSource (); Task. factory. startNew () => {try {var resu = data. asParallel (). withCancellation (cts. token ). where (d => d> 2); Console. writeLine ("query ended");} catch (OperationCanceledException ex) {Console. writeLine (ex. message); throw ;}}); Console. writeLine ("query start"); Console. writeLine ("cancel? "); String input = Console. ReadLine (); if (input. ToLower (). Equals (" y ") {cts. Cancel ();}

Add the WithCancellation () method to the parallel query. The parameter is CancellationToken. An OperationCanceledException exception is thrown when the query is canceled. You can use the Cancel () method to Cancel the query task after an exception is caught.

 

 

(4) Expression Tree

C # The Compiler defines different behaviors for a lambda Expression based on the type. When the type is Expression <T>, the compiler creates an Expression tree from the lambda Expression and stores it in the Assembly.

Example:

 1 static void Main(string[] args) 2 { 3     Expression<Func<int, bool>> expression = s => s > 1 ; 4     DisplayTree(0, "lambda", expression); 5     Console.ReadKey(); 6 } 7 static void DisplayTree(int indent, string message, Expression expression) 8 { 9     string outPut = string.Format("{0} {1} ! NodeType: {2}; Expr: {3}", "".PadLeft(indent, '>'), message, expression.NodeType, expression);10     indent++;11     switch (expression.NodeType)12     {13         case ExpressionType.Constant:14             ConstantExpression constExpr = (ConstantExpression)expression;15             Console.WriteLine("{0} Const Value: {1}", outPut, constExpr.Value);16             break;17         case ExpressionType.Equal:18         case ExpressionType.AndAlso:19         case ExpressionType.GreaterThan:20             BinaryExpression binExpr = (BinaryExpression)expression;21             if (binExpr.Method != null)22             {23                 Console.WriteLine("{0} Method: {1}", outPut, binExpr.Method.Name);24             }25             else26             {27                 Console.WriteLine(outPut);28             }29             DisplayTree(indent, "Left", binExpr.Left);30             DisplayTree(indent, "Right", binExpr.Right);31             break;32         case ExpressionType.Lambda:33             Console.WriteLine(outPut);34             LambdaExpression lambdaExpr = (LambdaExpression)expression;35             foreach (var item in lambdaExpr.Parameters)36             {37                 DisplayTree(indent, "Parameter", item);38             }39             DisplayTree(indent, "Body", lambdaExpr.Body);40             break;41         case ExpressionType.MemberAccess:42             MemberExpression memberExpr = (MemberExpression)expression;43             Console.WriteLine("{0} Member Name: {1}, Type: {2}", outPut, memberExpr.Member.Name, memberExpr.Type.Name);44             DisplayTree(indent, "Member Expr", memberExpr.Expression);45             break;46         case ExpressionType.Parameter:47             ParameterExpression parameExpr = (ParameterExpression)expression;48             Console.WriteLine("{0} Param Type: {1}", outPut, parameExpr.Type.Name);49             break;50         default:51             Console.WriteLine();52             Console.WriteLine("{0} {1}", expression.NodeType, expression.Type.Name);53             break;54     }55 }

 

Related Article

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.