Basic query operations and basic operations of LINQ

Source: Internet
Author: User

Basic query operations and basic operations of LINQ

1. How to Use LINQ

As a Data Query encoding method, LINQ is neither an independent development statement nor an application development method. In. NET3.5, You can integrate the LINQ query code in C. To use the LINQ query function in any source code file, you must reference the System. Linq namespace. To reference the System. XML. LINQ namespace using Linq to ADO. NET, you must reference the System. Data. LINQ namespace using Linq to ADO. NET.

2. LINQ query expression

Keyword of the query expression:

From: Specifies the data source and range variable to be searched. Multiple from clauses indicate that data is searched from multiple data sources.

Select: Specify the target data to be returned by the query. You can specify any type or even anonymous type.

Where: Specifies the filtering conditions for the elements. Multiple where clauses indicate the parallel relationship. Only when all the elements are met can they be selected.

Orderby: Specifies the sorting fields and sorting methods of elements. When there are multiple sorting fields, there is a field order to determine the primary-secondary relationship. You can specify the ascending and descending sorting methods.

Group: group field of the specified element.

Join: Specify the join method for multiple data sources.

2.1 use the from clause to specify the data source

Each LINQ query statement starts with the from clause. The from clause includes the following two functions:

● Specify the data source to be queried

● Define a local variable to indicate a single element in the data source

Example: from localval in datasource

Generally, you do not need to specify the data type for the localval element of the from clause. The compiler will assign an appropriate type to it based on the data source type, usually the type T in IEnumerable <T>. For example, the following val will be allocated as the int type.

Int [] arr = {1, 2, 3, 4, 5 };

Var query =

From val in arr

Select val;

In special cases, developers need to specify the data type for local variables. For example, in the above example, if you want to process the elements in arr as the object type, rather than the int type, you must specify val2 as the object type. Because the element in arr is of the int type and the child type of the Data object type, you can directly convert it as follows:

Int [] arr = {1, 2, 3, 4, 5 };

Var query =

From object val2 in arr

Select val2;

It is worth noting that the compiler does not check the specific types of local variables, so even if the specified type is incorrect, the compiler will not report an error, but when using this query below, will perform type check during running, resulting in exceptions.

2.2 Use the select clause to specify the target data

The LINQ query expression must end with a select or group clause. The target data to be selected in the select clause can not only be an element in the data source, but also different operation results of the element, including attributes, methods, and operations. The following two examples are shown:

var query2 =                from val in arr                select val.Name;            foreach(string item in query2)            {                Console.Write("{0},   ",item);            }            Console.WriteLine();            var query3 =                from val in arr                select val.Name.Length;            foreach (int item in query3)            {                Console.Write("{0},   ", item);            }

  In some special cases, the query results are usually used only temporarily, and the data of the query results includes many fields, not a simple attribute or method return value. In LINQ, the anonymous type can be used in the select clause to solve this problem. For example, the select clause in query4 defines the returned results through the anonymous type. Because the encoding cannot use the anonymous type, the foreach can only use the var (variable type) keyword to enable the compiler to automatically determine the element type in the query.

            var query4 =                from val in arr                select new { val.Name, val.Age,  NameLen = val.Name.Length};            foreach(var item2 in query4)            {                Console.WriteLine(item2);            }            

 

2.3 use the where clause to specify filtering Conditions

Purpose: Specify the filter conditions for the query.

Format: where Expression

Int [] ary = {1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

Var query =

From val in ary

Where (val> 5) & (val <10)

Select val;

2.4 sort with orderby clause

Purpose: sort the query results.

Format: orderby element [sortType]

SortType is an optional parameter, indicating the sorting type, including ascending and descending. The default value is ascending.

            int[] ary = { 9,54,32,1,67,43,0,9,7,4,9,2,23,66,61};            var query5 =                from val in ary                orderby val                select val;            foreach(var item in query5)            {                Console.Write("{0}   ",item);            }            Console.WriteLine();            Console.WriteLine();            var query6 =                from val in ary                orderby val descending                select val;            foreach (var item in query6)            {                Console.Write("{0}   ", item);            }

The result is:

In LINQ, orderby can specify multiple sorting elements at the same time or an independent sorting method for each sorting element. The first sorting element after orderby is the primary sorting, the second is the secondary sorting, and so on. In the following example, the names are listed in ascending order and then in descending order of age.

            var query7 =                from val in arr                orderby val.Name.Length ascending, val.Age descending                select val;            foreach(var item in query7)            {                Console.WriteLine(item);            }

Result:

2.5 grouping with group clauses

Role: grouping data

Format: group element by key

            var query8 =                from val in arr                group val by val.Xingbie;            foreach(var grp in query8)            {                Console.WriteLine(grp.Key);                foreach(var st in grp)                {                    Console.WriteLine("\t{0}",st);                }            }

Sometimes you need to sort the group results and query the results. In this case, you need to use the into keyword to store the group query results in a temporary variable, the new select or group clause must be used for query, orderby sorting, where filtering, and so on. The into statement format is as follows:

Group element by key into tmpgrp

Tmpgrp is a temporary variable used to temporarily Save the results generated by the group and provide subsequent query operations.

Var query9 = from val in arr group val by val. age into stgrp orderby stgrp. key descending select stgrp; foreach (var st in query9) {Console. writeLine ("{0} years old student:", st. key); foreach (var stu in st) {Console. writeLine ("\ t {0}", stu );}}

2.6 join clause

The join clause performs join operations to associate elements from different source sequences without any direct relationship in the object model. The only requirement is that the elements in each source need to be shared and can be compared, to determine whether the value is equal.

The join clause can implement three types of join: Internal join, Group join, and left external join.

2.6.1 use the join clause for internal join

Format: join element in datasource on exp1 equals exp2

Datasource indicates the data source. It is the second dataset to be used for join. element indicates the local variable for storing the elements in datasource. exp1 and exp2 indicate two expressions, which have the same data type, you can use equals for comparison. If exp1 and exp2 are equal, the current element is added to the query result.

            int[] intarray1 = { 5,15,25,30,33,40};            int[] intarray2 = { 10,20,30,40,50,60,70,80,90,100};            var query12 =                from val1 in intarray1                join val2 in intarray2 on val1 % 5 equals val2 % 15                select new { VAL1 = val1,VAL2 = val2};            foreach(var val in query12)            {                Console.WriteLine(val);            }    

2.6.2 grouping join with join clause

Format: join element in datasource on exp1 equals exp2 into kgname

The "into" keyword indicates that the data is grouped and saved to the "maid". The "maid" is a set of data.

Grouping joins produce layered data results. Each element in the first set is paired with a group of related elements in the second set. It is worth noting that even if the elements in the first set do not have any paired elements in the second set, an empty group object will be generated for it.

            var query13 =                from val1 in intarray1                join val2 in intarray2 on val1 % 5 equals val2 % 15 into grpName                select new { VAL1 = val1, VAL2 = grpName};            foreach(var val in query13)            {                Console.Write("{0}:  ",val.VAL1);                foreach(var obj in val.VAL2)                {                    Console.Write("{0}  ",obj);                }                Console.WriteLine();            }    

Compare the running results of query12 and query13.

2.6.3 use the join clause for left Outer join

The left Outer Join returns all elements of the first set element, whether or not it has related elements in the second set. In LINQ, DefaultEmpty () is called for the Group join result to execute the left Outer Join.

            var query14 =                from val1 in intarray1                join val2 in intarray2 on val1 % 5 equals val2 % 15 into grpName                from grp in grpName.DefaultIfEmpty()                select new { VAL1 = val1 , VAL2 = grp};            foreach(var val in query14)            {                Console.WriteLine(val);            }

2.7 use the let clause to extend the range variable

Used to create a range variable for the query itself

string[] strings ={                 "I am a new Student.",                 "You are a talent"                 };var query = from sentences in strings            let words = sentences.Split(' ')            from word in words            let w = word.ToLower()            where w[0] == 'a' || w[0] == 'e' || w[0] == 'i' || w[0] == 'o' ||                      w[0] == 'u'            select word;foreach (var word in query){    Console.Write(word + ",");}

Requirement: Outputs all the vowels in the two English statements in the string array to the console.

Analysis: First, traverse each string in the string array, use the let clause to create the query's own range variable words, and call the Split ('') method, separate each string with spaces and save the words into words. Then, use the let clause to create and query its own range variable word, and call the ToLower () method to change each word to lowercase, filter out the words whose first letter is the vowel and return the results.

PS: the complete code from: http://www.cnblogs.com/crandy/p/4546126.html

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.