This tutorial will give you an introduction to LINQ Queries using C#
A query is an expression that retrieves data from some type of data source. They are usually expressed in some type of query language that has been developed over time for all these types of data sources.
A good example could be SQL that is used for relational databases or XQuery which is used with XML. Consequently, developers have had to learn a different query language for each type of data source or format that they were working on. What LINQ does is offer a consistent model for working with data across various kinds of data sources and formats.
When working with LINQ queries you are always dealing with objects and the same basic coding patters to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format supported by a LINQ provider. All LINQ query operations consist of three distinct actions; obtain the data source, create the query, and executing the query.
Take into consideration this example below:
class IntroLINQ
{
static void Main()
{
// Here are the three parts of a LINQ query:
// 1 - Data source
int[] numbersCollection = new int[7] {6, 5, 4, 3, 2, 1, 0};
// 2 - Query creation
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbersCollection
where (num % 2) == 0
select num;
// 3 - Query execution
foreach (int num in numQuery)
{
Console.Write("{6,5} ", num);
}
}
} |
This shows how the three parts of a query operation are expressed in source code. Notice how it uses an array of type int as a data source for convenience. Keep in mind that the same concepts apply to other data sources as well.
In the code block above, the data source is an array that implicitly supports the generic IEnumerable(T) interface. By knowing this means it can be queried with LINQ. A query is then executed in a foreach statement, and each foreach statement requires IEnumerable or IEnumerable(T) . All types that support IEnumerable(T) or a derived interface such as the generic IQueryable(T) are called queryable types.
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
These queryable types require no modification or special treatment to serve as a LINQ data source. The LINQ provider must represent it as a source data if it is not already in memory as a queryable type. Here is an example of how LINQ to XML loads an XML document into a queryable XElement type below:
// Create a data source from an XML document.
// using System.Xml.Linq;
XElement contacts = XElement.Load(@"c:\myAddressBook.xml"); |
Ok, with LINQ to SQL, you first create an object-relational mapping at design time. Otherwise, you have to manually create it by using the Object Relational Designer. It works pretty straight-forward; you can write your queries against the objects, and then at run-time LINQ to SQL handles all the communication with the database.
Here is a perfect example of the People class encapsulating the database and “Women” represent a specific table within that database:
People db = new People(@"c:\people.mdf");
//Query for Women in Japan.
IQueryable<Women> custQuery =
from women in db.Women
where women.City == "Japan"
select women; |
When this query is executed it will return a sequence of Women objects, whose type is inferred by the compiler. The type of the query result, IQueryable(T), compiles to an expression tree, which is converted at run time into a SQL query.
A query specifies what to get from a data source(s). It can also specify how information should be sorted, grouped, and shaped before its returned. A query is stored in a query variable and initialized with a query expression. A C# query expression contains three clauses (reversed order of SQL): the from (specifies the data source), where (applies the filter), and select (specifies the type of the reutrned elements).
LINQ, the query variable itself, takes no action and returns no data. LINQ just stores the information that is required to produce the results when the query is executed at some later spot.
Keeping in mind that the query variable itself only stores the query commands; the concept of deferred execution, is when the query is deferred until it is iterated over the query variable in a foreach statement. The example below illustrates just this:
// Query execution
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
} |
Query results can be retrieved using a foreach statement. For instance, the iteration variable num (above), holds each value (one at a time) in the returned sequence. Since the query variable itself never holds the query results, it can be executed as many times as necessary.
Let’s say that you have a database that is being updated continually by a separate application. In this application, you could create one query that retrieves the latest data, and you could execute it repeatedly at some interval to retrieve different results every time.
Queries that perform aggregation functions over a range of source elements must first iterate over those elements. These queries include Count, Max, Average, and First. All those types of queries return a single value not an IEnumerable collection. Otherwise, a query that executes without explicit foreach statement is because the query itself must use foreach in order to return a result.
Take in this example of a query returns a count of the even numbers in a source array:
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;
int evenNumCount = evenNumQuery.Count(); |
In order to force immediate execution of any query and cache its results, you may call the ToList(TSource) or ToArray(TSource) methods as shown below:
List numQueryB =
(from num in numbers
where (num % 2) == 0
select num).ToList();
// or like this: // numQueryC is still an int[]
var numQueryC =
(from num in numbers
where (num % 2) == 0 \
select num).ToArray(); |
It is also possible to force execution by putting the foreach loop immediately after the query expression. Although, by calling ToArray() or ToList() you also cache all the data in a single collection object.
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.