Getting Started with Linq

Source: Internet
Author: User
Tags xquery

Advantages of LINQ:

A query is an expression that retrieves data from a data source.Queries are typically expressed in a specialized query language.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 a variety of data sources and data formats. in a LINQ query, objects are always used. you can use the same basic 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.

three parts of a query operation All LINQ query operations consist of the following three different operations:
    1. Gets the data source.

    2. Create a query.

    3. Executes the query.

A simple example:

  int[] numbers = new Int[7] {0, 1, 2, 3, 4, 5, 6};        2. Query creation.        Numquery is a ienumerable<int>        var numquery = from            num in numbers            where (num% 2) = = 0            Select Nu m;        3. Query execution.        foreach (int num in numquery)        {            Console.Write ("{0,1}", num);        }

Data source

In the previous example, because the data source is an array, it implicitly supports genericsIEnumerable<t> interface. This fact means that the data source can be queried in LINQ.Query inThe foreach statement is executed in the foreach  need   ienumerable  or   IEnumerable <t ; .  ienumerable &lt; T&gt; or a derived interface such as the generic iqueryable &lt; T&gt; is called queryable types. " > support IEnumerable <t ;   or derived interfaces (such as generics   IQueryable <t The type of ) is called queryable type.

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 the XML document.//using System.Xml.Linq; XElement contacts = xelement.load (@ "C:\myContactList.xml");

   In LINQ to SQL, first manually or using thethe Object Relational Designer (O/R Designer) creates an object-relational mapping at design time. Queries are written against these objects and then the communication to the database is handled by LINQ to SQL at run time.customers represents a specific table in the database, and the type of the query result, iqueryable &lt; T&gt;, derives from ienumerable&lt; T&gt;. " In the following example, customers  represents a specific table in the database, and the type of the query result is   IQueryable <t >   derived from   IEnumerable <t ; .

northwnd db = new Northwnd (@ "C:\northwnd.mdf");//Query for customers in London.iqueryable<customer> custquery = from Cust in db. Customers where Cust. City = = "London" Select Cust; 

  For more information about how to create a data source of a specific type, see the documentation for the various LINQ providers. But the basic rule is very simple: a LINQ data source is any object that supports a generic IEnumerable<t> interface or an interface inherited from that interface.

Inquire

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. to make it easier to write queries, C # introduces new query syntax.

The query in the previous example returns all the even numbers from an array of integers.The query expression consists of three clauses:FromWhere andSelect (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,The WHERE clause applies a filter,The SELECT clause specifies the type of element returned.these clauses and other query clauses are discussed in detail in the LINQ query expressions (C # Programming Guide) section. 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. For more information about how to build a query behind the scenes, see Standard query Operators overview

Execute Query

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, which is demonstrated in the following example:

  Query execution. foreach (int num in numquery) {    Console.Write ("{0,1}", num);}

  

foreach statement is also where the query results be retrieved." The foreach  statement is also where the query results are retrieved.  num holds each value (one at a time) I n the returned sequence. " For example, in the previous query, the iteration variable  num  saves each value in the returned sequence (one value at a time).

Because the query variable itself never saves the query results, you can execute the query as you want. For example, you can continuously update the database through a single application. in your application, you can create a query that retrieves the most recent data, and you can execute the query repeatedly at a time interval to retrieve different results each time.

Force immediate Execution

Queries that perform aggregate functions on a series of source elements must first iterate through the elements.CountMaxAverageAnd Firstbelong to this type of query.foreach statement because the query itself must use foreach in order to return a result. " Because the query itself must use &NBSP; foreach  to return results, so the queries do not use explicit   when they are executed; IEnumerable   collection.   The following query returns the count of even numbers in the source arrays: / span>

var evennumquery = from     num in numbers    where (num% 2) = = 0    Select Num;int evennumcount = Evennumquery.count () ;

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

list<int> NumQuery2 =    (from num in numbers     where (num% 2) = = 0     select num). ToList ();//or like this://NumQuery3 is still a int[]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.

Address: https://msdn.microsoft.com/zh-cn/library/bb397906.aspx

Learn more about Linq I only mention an address that is not duplicated, so it's easy to query quickly later

Overview of standard query Operators


Walkthrough: Writing a Query in C # (LINQ)

LINQ to SQL [LINQ to SQL]

LINQ to DataSet

LINQ to XML

LINQ to Objects

Getting Started with Linq

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.