C # Getting Started with LINQ (top)

Source: Internet
Author: User
Introduction to LINQ


Language-Integrated Query (LINQ) is an innovative feature introduced in Visual Studio 2008 and the. NET Framework version 3.5.


Traditionally, queries for data are represented as simple strings, without compile-time type checking or IntelliSense support. In addition, you must learn a different query language for each of the following data sources: SQL database, XML document, various WEB services, and so on. With LINQ, you can write queries against a strongly typed collection of objects using language keywords and familiar operators.

In Visual Studio, you can write LINQ queries for the following data sources: SQL Server databases, XML documents, ADO datasets, and any collection of objects that support the IEnumerable or generic ienumerable<t> interface 。


Usage requirements: Project ≥.net Framework 3.5.

I. INTRODUCTION of LINQ Queries


A query is an expression that retrieves data from a data source. Over time, people have developed different languages for various data sources, for example, SQL for relational databases and XQuery for XML. As a result, developers have to learn a new query language for each data source or data format that they must support.


LINQ simplifies this situation by providing a consistent model that uses data across data sources and data formats. In a LINQ query, objects are always used. You can use the same encoding pattern to query and transform data in XML documents, SQL databases, ADO datasets,. NET collections, and any other format for which the LINQ provider is available.

1.1 Three parts of a query operation


Operation Trilogy: ① fetch data source ② Create query ③ Execute Query

Internal class program{        private static void Main (string[] args)        {            //1. Get data source            var nums = new Int[7] {0, 1, 2, 3, 4, 5, 6};            2. Create Query            var numquery = from                num in nums                where (num% 2) = = 0                select num;            3. Execute Query            foreach (var num in numquery)            {                Console.WriteLine ("{0}", num);            }        }

Results:

0246

Shows the full query operation. In LINQ, the execution of a query is very different from the query itself; in other words, the query itself refers to creating only query variables and not retrieving any data.


1.2 Data sources


In the previous example, because the data source is an array, it implicitly supports the generic ienumerable<t> interface. Types that support ienumerable<t> or derived interfaces, such as generic iqueryable<t>, are called queryable types.

A queryable type can be used as a LINQ data source without modification or special processing. If the source data is not yet present in memory as a queryable type, the LINQ provider must represent the source data in this manner. For example, LINQ to XML loads an XML document into a queryable XElement type:

Create a data source from XML//using system.xml.linq;var contacts = xelement.load (@ "C:\xxx.xml");

In LINQ to SQL, you first need to create an object-relational mapping. Queries are written against these objects and then the communication to the database is handled by LINQ to SQL at run time.

var  db = new Northwnd (@ "C:\northwnd.mdf");//Query Client in London VAR custquery= from Cust in db. Customers                          where Cust. City = = "London"                          Select Cust;

Customers represents a specific table in a database


1.3 Queries


The query specifies the information to retrieve from the data source. Queries can also specify how to sort, group, and structure the information before returning it. The query is stored in a query variable and initialized with a query expression.


The query in the previous example is to return all the even numbers from an array of integers. The query expression consists of three clauses: from, where, and select. (If you are familiar with SQL, you will notice that the order of these clauses is the opposite of the order in SQL.) The FROM clause specifies the data source, where clause specifies that the filter is applied, and the SELECT clause specifies the type of element returned. It is important to note that in LINQ, the query variable itself does nothing and returns no data. It simply stores the information necessary to generate the results at a later time when the query is executed.


1.4 Query execution


1. Deferred execution


As mentioned earlier, the query variable itself simply stores the query command. The actual query execution is deferred until the query variable is cycled through the foreach statement. This concept is called "deferred execution."


2. Force immediate Execution


Queries that perform aggregate functions on a series of source elements must first iterate through the elements. Count, Max, Average, and first belong to this type of query. Because the query itself must use foreach to return results, these queries do not use explicit foreach statements when they are executed. Also note that these types of queries return a single value instead of a IEnumerable collection.

var numbers = new Int[7] {0, 1, 2, 3, 4, 5, 6};    var evennumquery = from        num in numbers        where (num% 2) = = 0        select num;    var evennumcount = Evennumquery.count ();

Results:

4

To force an immediate execution of arbitrary queries and to cache their results, you can call the Tolist<tsource> or Toarray<tsource> method.

var numQuery2 = (from num in numbers                                where (num% 2) = = 0                                select num). ToList ();    var numQuery3 = (from num in numbers                                     where (num% 2) = = 0                                     select num). ToArray ();

In addition, you can force a query by placing a foreach loop where it immediately follows the query expression. However, you can also cache all data in a single collection object by calling ToList or ToArray.

Second, the basic LINQ query operation

2.1 Get Data Source: from

In a LINQ query, the first step is to specify the data source. As in most programming languages, you must declare a variable before you can use it. In LINQ queries, the first use of the FROM clause is to introduce data sources and scope variables.

Queryallcustomers is ienumerable<cutsomer> type//Data source (customers) and range variable (cust) var queryallcustomers = from Cust in cus Tomers                        Select Cust;

A range variable is similar to an iteration variable in a foreach loop, but in a query expression, the iteration does not actually occur. When you execute a query, the range variable is used as a reference to each successive element in customers. Because the compiler can infer the type of Cust, you do not have to explicitly specify this type.

2.2 Filtering: where


Perhaps the most common query operation is to apply a filter in the form of a Boolean expression. This filter causes the query to return only those elements whose expression result is true. Use the WHERE clause to generate the results. In effect, a filter specifies which elements are excluded from the source sequence.

var querylondoncustomers = from Cust in Customers   where Cust. City = "London"    Select Cust;           

You can use the familiar C # logic and (&&) and OR (| | operator to apply any number of filter expressions in the WHERE clause as needed.

Where Cust. City = "London" && Cust. Name = "Devon" where Cust. City = "London" | | Cust. Name = "Paris"

2.3 Reviews sorted By:

It is generally easy to sort the returned data. The ORDER BY clause causes the elements in the returned sequence to be sorted according to the default comparer for the type being sorted.

var querylondoncustomers = from Cust in Customers                               where Cust. City = "London" is                               Cust. Name descending                                Select Cust;

Because Name is a string, the default comparer performs an alphabetical sort from a to Z. To sort the results in reverse order (from Z to A), use the orderby...descending clause.

2.4 Group: Group

Using the group clause, you can group the results by the specified key.

var querylondoncustomers = from Cust in Customers                    group Cust by Cust. City;    foreach (Var querylondoncustomer in querylondoncustomers)    {       Console.WriteLine (querylondoncustomer.key);       foreach (Var cust in Querylondoncustomer)       {          Console.WriteLine (Cust. Name);       }    }

You can specify that the results should be grouped by city so that all customers in London or Paris are in their respective groups.

In this case, Cust. City is the key.

When you end a query by using the group clause, the result takes the form of a list. Each element in the list is an object that has a key member and a list of elements grouped by the key. When iterating through queries that generate group sequences, you must use nested foreach loops. The outer loop is used to iterate through each group, and the inner loop is used to iterate through the members of each group.

If you must reference the results of a group operation, you can use the INTO keyword to create identifiers that can be queried further.

Custquery is ienumable<igrouping<string, customer>> type    var custquery = from Cust in Customers                    Group Cust by Cust. City into                    CustGroup                    where Custgroup.count () > 2 by                    custgroup.key                    Select CustGroup;

The query here only returns those groups that contain more than two customers.

2.5 Joins: Join

Join operations create associations between sequences in the data source that do not have an explicit modeling. For example, you can perform a join to find all customers and resellers in the same location. In LINQ, a join clause is always run against a collection of objects rather than directly against a database table.

var innerjoinquery = from Cust in Customers                     joins Dist in distributors on Cust. City equals Dist. City                     Select New {CustomerName = cust. Name, Distributorname = Dist. Name};

In LINQ, a join clause is always run against a collection of objects rather than directly against a database table.

In LINQ, you do not have to use joins as frequently as in SQL, because foreign keys in LINQ are represented in the object model as properties that contain collections of items.

From order in customer.orders ...

2.6 Selection (projection): Select

The SELECT clause generates a query result and specifies the shape or type of each returned element.

For example, you can specify whether the result contains the entire Customer object, only one member, a subset of members, or a completely different result type based on a calculation or new object creation. When a SELECT clause generates something other than a copy of the source element, the operation is called projection.

Iii. using LINQ for data conversion

Language-Integrated Query (LINQ) is not only useful for retrieving data, but it is also a powerful data transformation tool. By using a LINQ query, you can use the source sequence as input and modify it in several ways to create a new output sequence. You can modify the sequence by sorting and grouping without having to modify the element itself. However, the most powerful feature of LINQ queries is the ability to create new types. This feature is implemented in the SELECT clause. For example, you can perform the following tasks:

3.1 Joining multiple inputs to an output sequence

Class Student    {public        string Name {get; set;}        public int Age {get; set;}        public string City {get; set;}        Public list<int> Scores {get; set;}    }    Class Teacher    {public        int Id {get; set;}        public string Name {get; set;}        public int Age {get; set;}        public string City {get; set;}    }

Two classes of students and teachers

Internal class Program {private static void Main (string[] args) {//Create First data source Var s tudents = new List<student> () {new Student () {age = 23 , city = "Guangzhou", Name = "Small C", Scores = new list<int> () {85, 88, 83,97}}, New Student () {age =, Cit                 y = "Guangxi", Name = "Xiaoming", Scores = new list<int> () {86,78,85,90}},                    New Student () {age = $, city = "Dream",            Name = "Small Three", Scores = new list<int> () {86,68,73,97}}};                Create a second data source var teachers = new List<teacher> () {New Teacher () {Age= +, City = "Dream", Name = "Kiss"}, New Teacher ()                {age = +, city = "Yunnan", Name = "Little Red"},                    New Teacher () {age = $, city = "Henan",            Name = "Lili"}; Create query var peopleindreams = (from student in students where student. City = = "Dream" select student. Name). Concat (from teacher in teachers where teacher. City = = "Dream" Select Teacher.            Name);            Execute query foreach (var person in Peopleindreams) {Console.WriteLine (person);        } console.read (); }    }

This is what C # has started using LINQ (above), and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.