Basic knowledge of LINQ

Source: Internet
Author: User

Agenda

1. LINQ and LINQ expressions

2. Lambda expressions

Two interfaces

Ienumerable <t> generic interface

Public enumeration number, which supports simple iteration on a set of the specified type.

Public class mycollections <t>: ienumerable <t>

{

T [] values = new T [100];

Public ienumerator <t> getenumerator ()

{

For (INT I = 0; I <100; I ++)

{

Yield return values [I];

}

}

Ienumerator ienumerable. getenumerator ()

{

Return getenumerator ();

}

}

Class class2

{

Static void main ()

{

Mycollections <int> mycol = new mycollections <int> ();

Foreach (int I in mycol)

{

Console. writeline (I );

}

}

}

Iqueryable <t>

Provides the function of calculating queries for specific data sources with known data types.

This interface inherits the ienumerable <t> interface. Therefore, if it represents a query, You can enumerate the query results. The enumeration forces the expression directory tree associated with the iqueryable <t> object.

Basic Concepts

LINQ: Language Integrated Query is a collection of standard query operators that navigate almost every data source, both filtering and execution provide the underlying basic query architecture.

Data sources that can be queried by LINQ include relational data, XML, dataset, or data in memory.

Background of the emergence of LINQ: Most developers are familiar with OO, and it is best to convert operations on data into operations on objects.

The standard query function is directly integrated into the. NET-based programming language for developers.

The focus of the LINQ clause is the query expression because it describes the specific operations on the data source.

Basic concepts of LINQ Query expressions

1. the query expression can be used to query and convert data from any data source that supports LINQ. For example, a single query can retrieve data from an SQL database and generate an XML Stream as the output.

2. Query expressions are easy to understand because they are constructed using many common C # languages.

3. variables in the query expression are strongly typed, but in many cases you do not need to explicitly provide the type because the compiler can infer the type.

4. the query will not be executed until you cyclically access the query variables in the foreach statement.

5. During compilation, the query expression is converted to the "standard query operator" method according to the rules set in the C # specification. Any query that can be represented by the query syntax can also be represented by the method syntax. However, in most cases, the query syntax is easier to read and concise.

6. As a rule for writing a LINQ query, we recommend that you use the query syntax whenever possible and use the method syntax only when necessary. The two forms have no difference in semantics or performance. Query expressions are generally easier to read than Equivalent Expressions written in method syntax.

7. Some query operations, such as count or Max, do not have an equivalent query expression clause, so they must be represented as method calls. Method syntax can be combined with query syntax in multiple ways.

8. The query expression can be compiled into the expression directory tree or delegate, depending on the type applied to the query. Ienumerable <(of <(T>. Iqueryable and iqueryable <(of <(T>) are compiled into the expression directory tree.

LINQ query expression

The query operation consists of three parts:

  1. Get Data Source
  2. Create Query
  3. Execute Query

Demo:

// Obtain the data source

String [] devices = {"TV", "refrigerator", "washing machine", "phone", "microwave oven "};

// Create a query

VaR selectdevices = from device in devices

Where device. startswith ("electricity ")

Select device;

// Execute the query

Foreach (string Dev in selectdevices)

{

Console. writeline ("Live device: {0}", Dev );

}

Anonymous Method

In C # versions earlier than 2.0, the only way to declare a delegate is to use the naming method. C #2.0 introduces anonymous methods. In C #3.0 and later versions, lambda expressions replace anonymous methods as the preferred method for writing Inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. In one case, the anonymous method provides functions not available in lambda expressions. The anonymous method allows you to omit the parameter list, which means you can convert an anonymous method to a delegate with various signatures. This is not possible for lambda expressions.

Button1.click + = delegate (system. Object o, system. eventargs e) // anonymous method parameter

{// Anonymous method body

MessageBox. Show ("Click! ");

};

 

 

Lambda expressions

  • A Lambda expression is an anonymous function that can contain expressions and statements and can be used to create a delegate or expression directory tree.
  • All lambda expressions use the lambda operator =>, which reads "goes ". The left side of the lambda operator is the input parameter (if any), and the right side contains the expression or statement block. Lambda expressions x => X * X are read as "X goes to X times X ". This expression can be assigned to the delegate type.

Static void main ()

{

Del mydelegate = x => X * X;

Int J = mydelegate (5); // J = 25

Console. writeline (j );

}

Delegate int del (int I );

  • Parentheses are optional only when Lambda has an input parameter; otherwise, parentheses are required. Two or more input parameters are separated by commas (,) enclosed in parentheses:

(X, y) => X = y

  • Sometimes, the compiler is difficult or unable to deduce the input type. In this case, you can explicitly specify the type as shown in the following example:

(Int x, string S) => S. length> X

The ulambda statement is similar to the lambda expression, but the statement is enclosed in braces:

Delegate void testdelegate (string S );

...

Testdelegate MYDEL = n => {string S = N + "" + "world"; console. writeline (s );};

MYDEL ("hello ");

  • When writing lambda, you usually do not need to specify a type for the input parameter, because the compiler can infer the type based on the lambda subject, basic delegate type, and other factors described in the C #3.0 language specification. For most standard query operators, the first input is the type of elements in the source sequence. Therefore, if you want to query ienumerable <customer>, the input variable is inferred to be of the customer type, which means you can access its method and attributes:

Customers. Where (C => C. City = "London ");

  • Sometimes, the compiler is difficult or unable to deduce the input type. In this case, you can explicitly specify the type as shown in the following example:

(Int x, string S) => S. length> X

The ulambda statement is similar to the lambda expression, but the statement is enclosed in braces:

Delegate void testdelegate (string S );

...

Testdelegate MYDEL = n => {string S = N + "" + "world"; console. writeline (s );};

MYDEL ("hello ");

  • When writing lambda, you usually do not need to specify a type for the input parameter, because the compiler can infer the type based on the lambda subject, basic delegate type, and other factors described in the C #3.0 language specification. For most standard query operators, the first input is the type of elements in the source sequence. Therefore, if you want to query ienumerable <customer>, the input variable is inferred to be of the customer type, which means you can access its method and attributes:

Customers. Where (C => C. City = "London ");

The general rules of Lambda are as follows:

  • Lambda must contain the same number of parameters as the delegate type.
  • Each input parameter in Lambda must be implicitly converted to its corresponding delegate parameter.
  • The return value (if any) of Lambda must be implicitly converted to the return type of the delegate.

Lambda can reference "external variables" that are within the range of a closed method or type in which Lambda is defined. Variables captured in this way will be stored for use in lambda expressions, even if the variables are otherwise out of range or recycled as garbage. An external variable must be explicitly allocated before it can be used in a Lambda expression.

  • The captured variables will not be recycled as garbage until the delegation of the referenced variables exceeds the permitted range.
  • Variables introduced in lambda expressions cannot be seen in external methods.
  • Lambda expressions cannot directly capture the ref or out parameters from the closed method.
  • The Return Statement in the lambda expression does not cause the return of the closed method.
  • Lambda expressions cannot contain goto statements, break statements, or continue statements whose target is located outside or inside the body of the anonymous function.

Query syntax and method syntax

String [] devices = {"TV", "refrigerator", "washing machine", "phone", "microwave oven "};

Query syntax

VaR selectdevices = from device in devices

Where device. startswith ("electricity ")

Select device;

Method syntax

VaR selectdevices = devices. Where (device => device. startswith (" "))

Foreach (string Dev in selectdevices)

{

Console. writeline ("Live device: {0}", Dev );

}

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.