Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use keywords in LINQ

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use keywords in LINQ". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use keywords in LINQ.

What is LINQ?

LINQ, short for Language Integrated Query, is a feature integrated into the .NET programming language. It has become an integral part of the programming language, and it can get the benefits of strong typed languages such as compile-time syntax checking, rich metadata, intelligent awareness, static typing and so on. And it also makes it easy to query the information in memory, not just the external data source.

LINQ includes LINQ to Objects,LINQ to SQL, LINQ to XML, LINQ to DataSet, etc. This article starts with LINQ to Objects to understand the surface of LINQ.

What you need to know before you start LINQ

Expansion method

As the name implies, an extension method can add a common interface to an existing class (not interface in C #) without modifying the existing class.

An extension method is essentially a static method, except that its * * parameters must be declared with the this keyword, and the type of * parameters is the type to be extended. Such as

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 that converts a string to a double type. As long as the namespace of the method is referenced, the ToDouble method can be called directly with the string type.

The extension method is the basis of the following article. The implementation of LINQ in C # 3.0 is based on the extension method. The related functions of IEnumerable are realized through the expansion of the IEnumerable interface (LINQ to Objects) and the extension of IQueryable, and the related keywords of LINQ are finally transformed into the call to IEnumerable (IQueryable).

Lambda expression

Lambda expressions are actually anonymous methods in .net 2.0, which are then presented in a more elegant manner in 3.0.

The basic syntax of an lambda expression is

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

(parameter list) = > expression

Parentheses can be omitted when there is only one parameter in the parameter list

Func func = x = > x + x; Console.WriteLine (func ("a"))

Var: implicitly typed variables

Using declarations with variables that can be deduced by the compiler, there is no need to explicitly specify the type of the object.

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

In the above example, because the type of the object is already specified in the definition, it is no longer necessary to use the displayed type definition in the declaration, so the var keyword can be used.

For anonymous objects

Var test = new {Name = "Sth.", Type = "UnKnown"}

Since you cannot declare an anonymous object with a type class, you can declare it with var.

Note that var only saves the process of explicit declaration, while C # itself is a static language, so the type of variable declared by var has been determined to be immutable, that is, var is not a variant type.

To whom is LINQ applicable?

LINQ's syntax is supported by the Enumerable class under System.LINQ. By looking at his signature, you will find that he has implemented a series of extension methods for IEnumerable, that is, any object that implements IEnumerable can be queried using LINQ syntax.

For objects that only implement the IEnumerable interface but not IEnumerable, you can use the

Public static IEnumerable Cast (this IEnumerable source)

To convert the IEnumerable interface to IEnumerable (for example, ArrayList).

Keywords in LINQ

In LINQ 3.0, some new keywords have been introduced. They are:

From join where group into let orderby select

Do students who are familiar with Sql look familiar? in fact, their meaning in LINQ is similar to that in SQL, so it will be easy to understand. In the following time, we will briefly introduce the use of these keywords.

From

The from clause is the beginning of a LINQ query, and any LINQ statement starts with from, and the from clause specifies the container of the query, and the local variables that are valid in this statement (used to specify an item in the container, the from clause works much like foreach). The syntax of the from clause is

From local in containerlocal

This is the local variable in this LINQ statement, and since container must be IEnumerable, its type can be derived from container (that is, T). A simple example from the previous paragraph:

Var container = new List {"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 container implements only IEnumerable but not IEnumerable, you need to explicitly specify the type of local variable, or use Cast to convert to IEnumerable

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

Project the result of the query and specify the column to be selected in the clause, as in the example above

Sometimes, we just need to project a certain column, and 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 collection of columns to project, at which point we use anonymous types

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);}

Every item in query is an object with an ID attribute and a Name attribute. Of course, sometimes the attribute name of the entity is not what we want, or it is calculated from the attribute, so we can explicitly specify the attribute name, like the following:

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.nameswitjoin

Similar to the join clause in join,LINQ in SQL, it is used to associate the data of two containers with some kind of 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 and not other operators (not even = =). The left side of the equals operator must join the left part, and the right part must be the right part, which cannot be exchanged, otherwise the compilation will not pass.

Into

The into clause is used to further persist the result of the join or group clause, wrapping it into a

System.LINQ.IGrouping

Object, and IGrouping inherits from IEnumerable, you can see that the IGrouping interface provides the grouped key and the collection contained under that key. For an example, see group

Group

Group the results according to the specified conditions

Var container = new List {"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 demonstrates that a list of names is grouped by the length of names, and the result of the grouping is kept in the local variable g. The result of query can be output by the following code

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 later 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 extensions on IEnumerable

Take Skip

Used to select the first XX or skip the front XX, such as 11 to 20

Query.Skip (10). Take (10); OrderBy OrderByDescending

It's just sorting.

Query.OrderBy (c = > c.Length); Distinct Union Intersect Except have all been seen before, that is, whether or not to repeat, union, intersection, and difference (this seems to be understood by looking at the parameters).

. The other extensions are under the Enumerable class.

Delayed loading characteristics of LINQ

The execution result of the LINQ query is of type IEnumerable, while for IEnumerable, internally, C # implements an iterator through the yield keyword to achieve delayed loading. As a result, LINQ queries are executed only when needed.

However, some extension methods attempt to traverse the entire container when executed, invalidating deferred loading, such as sorting, aggregate functions (Count,Sum,Average, etc.). )

Static IEnumerable 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 using Take, the LINQ statement executes normally, but when we use an Order By on LINQ, the program gets stuck. Of course, this should be taken for granted. After losing the delayed loading feature, the result of trying to sort an infinite sequence must be outOfMemory.

Thank you for your reading, the above is the content of "how to use keywords in LINQ". After the study of this article, I believe you have a deeper understanding of how to use keywords in LINQ, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report