) LINQ learning notes

Source: Internet
Author: User
ArticleDirectory
    • Who is applicable to LINQ?
    • Other extensions on ienumerable <t>
    • Latency loading of LINQ
Preface

I recently read this article in the blog post on LINQ, which is easy to understand and can be shared with you. Original address http://www.cnblogs.com/goscan/archive/2011/05/05/Linq_study_log.html

What is LINQ?

LINQ is short for Language Integrated Query, which is integrated in. net.Programming Language. Has become an integral part of the programming language.ProgramThe compilation syntax check, rich metadata, smart sensing, static type, and other advantages can be obtained. In addition, it also enables queries to conveniently Query Information in the memory, not just external data sources.

This article describes the basics of LINQ to objects.

The extension method you need to know before you start LINQ

As the name implies, it is a method for extending existing classes. The extension method can add public interfaces (not interfaces in C #) for existing classes without modifying existing classes ).

An extension method is essentially a static method. The difference is that its first parameter must have the this keyword declaration, and the type of the first parameter is the type to be extended. For example

Public static doubleTodouble (This stringSource ){DoubleRes = 0d;Double. Tryparse (source,OutRes );ReturnRes ;}Public static voidSimpleextesionmethod (){DoubleD ="12345.54321". todouble ();Console. Writeline (d );}

Here is a simple extension method to convert a string to the double type. As long as the namespace of the method is referenced, The todouble method can be called directly using the string type.

The extension method is the basis of the post-article, and the implementation of LINQ in C #3.0 is based on the extension method, through the ienumerable <t> interface (LINQ to objects) and the iqueryable <t> extension to implement related functions of LINQ, and the related keywords of LINQ are eventually converted into calls to ienumerable <t> (iqueryable <t>.

Lambda expressions

Lambda expressions are actually the anonymous method in. net2.0, and are then presented in a more elegant way in 3.0.

The basic syntax of lambda expressions is

(Parameter list) =>{ statement block;} or

(Parameter list) => Expression

When there is only one parameter in the parameter list, parentheses can be omitted.

 
Func<String,String> Func = x => X + X;Console. Writeline (func (""));
VaR: implicitly typed variable

You do not need to explicitly specify the object type.

VaRContainer =NewList<String> {"James","Li Si","Wang Wu"};Ienumerable<String> Query =FromNameInContainerSelectName;

In the preceding example, because the object type is specified in the definition, it is not necessary to use the displayed type definition in the declaration. Therefore, you can use the VaR keyword.

For anonymous objects

 
VaRTest =New{Name ="Something .", Type ="Unknown"};

Because an anonymous object cannot be declared using a type class, VaR can be used as the declaration.

Note that VaR only saves the explicit declaration process, and C # itself is a static language. Therefore, the type of the variable declared by VAR cannot be changed, that is, vaR is not a variant type.

Who is applicable to LINQ?

Using the system. the enumerable class under LINQ provides support. By observing his signature, you will find that he has implemented a series of extension methods for ienumerable <t>, that is, any object that implements ienumerable <t> can be queried using the LINQ syntax.

For objects that only implement the ienumerable interface but not the ienumerable <t>

 
Public static ienumerable <tresult>Cast<Tresult> (This ienumerable source );

To convert the ienumerable interface to ienumerable <t> (for example, arraylist ).

Keywords in LINQ

In C #3.0, some new keywords are introduced for LINQ. They are:

From join where group into let orderby select

If you are familiar with SQL, are you familiar with SQL? In fact, their meanings in LINQ are similar to those in SQL, so they are easy to understand. Next, we will briefly introduce the use of these keywords.

From

The from clause is the start of a LINQ query. Any LINQ statement starts with the from clause. The from clause specifies the container to be queried and the local variables valid for this statement (used to specify one of the containers, the effect of the from clause is similar to that of foreach ). The syntax of the from clause is

 
 FromLocalInContainer

Local is the local variable in this LINQ statement. Because container must be ienumerable <t>, its type can be derived from container (that is, t ). The previous simple example:

VaRContainer =NewList<String> {"James","Li Si","Wang Wu"};VaRQuery =FromNameInContainerSelectName;Foreach(StringNameInQuery ){Console. Writeline (name );}

Output

 
Zhang sanli Si Wang Wu

If the container only implements ienumerable but does not implement ienumerable <t>, You need to explicitly specify the type of the local variable, or use cast to convert it to ienumerable <t>

 
VaRContainer =NewArraylist{"James","Li Si","Wang Wu"};VaRQuery =FromNameInContainer. Cast <String> ()SelectName;
 
// OrVaRQuery1 =From stringNameInContainerSelectName;
Select

Project the query results. In the clause, specify the columns to be selected. For example

Sometimes, we only need to project a column. We can do this.

 
Private Static voidTestselectsingleproperty (){VaRPersons = getpersons ();VaRQuery =FromPInPersonsSelectP. Name;Foreach(VaRItemInQuery ){Console. Writeline (item );}}

We can also specify the set of columns to be projected. In this case, we need to use the anonymous type.

VaRQuery =FromPInPersonsSelect New{P. ID, P. name };Foreach(VaRItemInQuery ){Console. Writeline ("No: {0}, name: {1 }", Item. ID, item. Name );}

Each item in a query is an object with the ID attribute and name attribute. Of course, sometimes the attribute name of an object is not what we want, or is calculated based on the attribute, you can explicitly specify the attribute name, as shown below:

VaRQuery =FromPInPersonsSelect New{Userid = P. ID, friendname = P. Gender ="Male"?"Mr":"Ms"+ P. name };Foreach(VaRItemInQuery ){Console. Writeline ("No: {0}, friendly name: {1 }", Item. userid, item. friendname );}

Where

Filter the data in the container.

VaRQuery =FromPInPersonsWhereP. Required mentid = 1SelectP. Name;

Join

Similar to the join clause in SQL, the join clause in LINQ is used to associate the data of two containers in a certain relationship.

 
VaRAdministrative ments = getadministrative ments ();VaRPersons = getpersons ();VaRQuery =FromDInAdministrative mentsJoinPInPersonsOnD. idEqualsP. initialize mentidSelect New{D, p };

It is worth noting that the join clause can only use equals or not equal, but not other operators (= ). The left part of the equals operator must be connected, and the right part cannot be changed. Otherwise, compilation cannot pass.

Into

The into clause is used to continue the results of join or group clauses and encapsulate them into

System. LINQ. igrouping <tkey, telement>

And igrouping inherits from ienumerable <telement>. You can see that the igrouping interface provides the grouping key and the set contained in the key. For example, see Group

Group

Grouping results based on specified conditions

VaRContainer =NewList<String> {"Zhangsan","Lisi","Wangwu","Zhaoliu","Deng"};VaRQuery =FromNameInContainerGroupNameByName. LengthIntoGSelect New{G. Key, values = g };

The example shows how to group A Name List by name length and keep the grouping result to the local variable G.CodeOutput query results

Foreach(VaRGroupInQuery ){Console. Writeline ("{0 }:", Group. Key );Foreach(VaRItemInGroup. Values ){Console. Writeline (item );}}
Let

The let clause is used to add a new local variable to the query to make it visible in subsequent queries.

VaRQuery =FromPInPersonsLetFriendlyname = P. Gender ="Male"?"Mr":"Ms"+ P. NameSelect New{Userid = P. ID, friendname = friendlyname };Foreach(VaRItemInQuery ){Console. Writeline ("No: {0}, friendly name: {1 }", Item. userid, item. friendname );}

Other take skip extensions on ienumerable <t>

Used to select the first XX or skip the first XX. If you select 11th to 20, you can

 
Query. Skip (10). Take (10 );
Orderby orderbydescending

Sorting

 
Query. orderby (C => C. Length );

The words distinct Union intersect except t have been seen. They are not repeated, union, intersection, and difference set. (This seems to be clear when you look at the parameters)

.... All other extensions are under the enumerable class.

Latency loading of LINQ

The execution result of the LINQ query is ienumerable <t> type. For ienumerable <t>, inside, C # uses the yield keyword to implement the iterator to achieve delayed loading. In this way, the LINQ query is executed only when necessary.

However, some extension methods attempt to traverse the entire container during execution, so that delayed loading is ineffective, such as sorting and Aggregate functions (count, sum, average, etc .)

 Static  Ienumerable < Int > Infinityints (){ Int Count = 0; While ( True )Yield return Count ++ ;} Public static void Lazyload (){ VaR Query = From I In Infinityints () Select I; Foreach ( VaR I In Query. Take (20 )){ Console . Writeline (I );}} Public static void Cantdolazyload (){ VaR Query = From I In Infinityints () Select I; Foreach ( VaR I In Query. orderby (I => I). Take (20 )){ Console . Writeline (I );}}

Here is a simple example to prove that when taking is used, the LINQ statement can be executed normally, and when we use an order by statement on LINQ, the program will be stuck. Of course, this is justified. After the delayed loading feature is lost, the result of trying to sort an infinite sequence must be outofmemory.

Last

This is just a fur. If you are interested, you can go to msdn to view more detailed information. Finally, we recommend a tool and a website.

Linqpad (http://www.linqpad.net/) a very useful LINQ learner

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.