Queries

A query is a string expression that retrieves data from a data source. The expression is usually related to a particular data source such as SQL or XML and will generally be expressed in that respective data source language. However, with LINQ, we can develop a reusable coding pattern that works on different data sources. The pattern is divided into three parts: 

  • Obtaining the data source
  • Creating the query
  • Executing the query

The following code that illustrates the three operations in their simplest forms:

// 1. Obtaining the data source.
int[] numbers = new int[3] { 0, 1, 2};
// 2. Query creation.
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}

In the preceding code example, we created an array of integers whose size is 3. As it implements the IEnumerable<int> interface, we will be able to implement LINQ on the array. In the next step, we created a query in which we are filtering even numbers present in the array. Finally, in the third step, we are looping through the results of the query execution and printing it.

In the preceding example, we used an array as the source of data. The array already supports the IEnumerable or IEnumerable <T> interface. However, in some cases, that may not always be the case. For example, when we read the data source from sources such as XML files, we need LINQ to load the data in memory as a queryable type. In this case, we can use the XElement type. The following is the syntax for this:

// Create a data source from an XML document. // 
using System.Xml.Linq;

XElement students = XElement.Load(
@"c:students.xml");

In the preceding code example, we have loaded the data from the XML file in the XElement object, which implements an IQuerable interface. Now, on this, we can easily write LINQ queries to execute any operation.

Before we move ahead and understand more around LINQ, we must understand the built-in features of C# that help us implement LINQ queries. In the next section, we will discuss some of these features.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.154.252