Linq learning notes

Source: Internet
Author: User
Document directory
  • Extension Method
  • Lambda expressions
  • Var: implicitly typed variable
  • Who is applicable to Linq?
  • From
  • Select
  • Where
  • Join
  • Into
  • Group
  • Let
  • Other extensions on IEnumerable <T>
  • Latency loading of Linq
Abstract: The existence of LINQ is to make your. NET development journey smoother. Here we will share with you some of the details in the Development of LINQ, hoping to help you. Preface

As a matter of fact, I have already studied Linq in and was attracted by her beautiful syntax, but my company is still using VS2005. the development under the Net2.0 framework has not been used for a long time. Recently, my colleagues in the Department are interested in this, so I plan to sort out something and share it with you.

What is Linq?

LINQ is short for Language Integrated Query. It is a feature Integrated in. NET programming languages. It has become an integral part of programming languages. During programming, you can get good syntax check, rich metadata, smart sensing, static type, and other advantages of strong language. 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 double ToDouble(this string source) {     double res = 0d;     double.TryParse(source, out res);     return res; } public static void SimpleExtesionMethod() {     double d = "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("a")); 
Var: implicitly typed variable

You do not need to explicitly specify the object type.

Var container = new List <string> {"Zhang San", "Li Si", "Wang Wu"}; IEnumerable <string> query = from name in container select name;

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

var test = new { Name = "Sth.", 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

 from local in container

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:

Var container = new List <string> {"Zhang San", "Li Si", "Wang Wu"}; var query = from name in container select name; foreach (string name in query) {Console. writeLine (name );}

Output

Zhang San, Li 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>

Var container = new ArrayList {"Zhang San", "Li Si", "Wang Wu"}; var query = from name in container. Cast <string> () select name;
// Or var query1 = from string name in container select name;
Select

Project the query results. In the clause, specify the columns to be selected, as shown in the preceding example.

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

private static void TestSelectSingleProperty() {     var persons = GetPersons();     var query = from p in persons                 select p.Name;     foreach (var item in query)     {         Console.WriteLine(item);     } }

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

var query = from p in persons             select new { p.ID, p.Name }; foreach (var item in query) {     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:

Var query = from p in persons select new {UserID = p. ID, FriendName = p. Gender = "male "? "Mr": "Ms" + p. name}; foreach (var item in query) {Console. writeLine ("No: {0}, Friendly Name: {1}", item. userID, item. friendName );}
Where

Filter the data in the container.

var query = from p in persons             where p.DepartmentID == 1             select p.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.

var departments = GetDepartments(); var persons = GetPersons(); var query = from d in departments             join p in persons on d.ID equals p.DepartmentID             select 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

var container = new List<string> { "ZhangSan", "LiSi", "Wangwu", "ZhaoLiu", "Deng" }; var query = from name in container             group name by name.Length into g             select 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. You can use the following code to output the query result.

foreach (var group in query) {     Console.WriteLine("{0}:", group.Key);     foreach (var item in group.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.

Var query = from p in persons let friendlyName = p. Gender = "male "? "Mr": "Ms" + p. name select new {UserID = p. ID, FriendName = friendlyName}; foreach (var item in query) {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 learning tool

The official code samples of Microsoft's Linq 101

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.