An Introduction to Language-Integrated Query (LINQ) C#


Server Intellect


An Introduction to Language-Integrated Query (LINQ) C#

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.



Comments
maryam said:

good tutorial

thanks

Posted 02/28/2010 at 4:05 AM
Amol Kothawade said:

Nice tutorial.

Thanks.

Posted 03/08/2010 at 12:07 AM
Aravind said:

Nice one, Keep going .. :-)

Posted 03/09/2010 at 5:11 AM
Silky said:

Nice tutorial

Thanks

Posted 03/11/2010 at 4:32 AM
Arjun said:

Awesome tutorial

Posted 03/19/2010 at 1:45 AM
leather sandals said:

One important point that may seem obvious but is worth calling out anyway, is that running streaming queries more than once results in reading through the entire stream each time. So to best apply this technique, you should try to extract everything you need from the XML content in one pass (that is, with one LINQ query). If it turns out that you need to query over the stream multiple times, you’ll need to reconsider matters to determine if you aren’t better off caching the XML content once and then querying over the in-memory cache multiple times.

Posted 03/29/2010 at 12:15 PM
bible experience said:

The IBM Data Server Provider for .NET lets you take advantage of the Microsoft Entity Framework using IBM data servers (DB2, IDS, and U2). You can generate Entity Data Model (EDM) schemas, and you can write and execute EntitySQL and LINQ statements to Entities applications with the supported IBM data server versions. It enables developers to query and manipulate data using a conceptual model instead of a physical storage model.

Posted 03/29/2010 at 12:15 PM
Essay said:

I have a strong feeling that the author has got tremendous experience in teaching. Here he sheds light on LINQ Queries using C#. First of all he explains what a query is and then he gives an example to substantiate his point. A brief overview of LINQ queries and its operations is provided thereafter. After that he proceeds to the most important part – the programming part. The program is presented in meticulous detail. It is written in such a way that even a novice can use it. This is certainly a useful blog to computer programmers and it is written in very simple English.

Posted 05/04/2010 at 8:56 PM
http://www.linqhelp.com/ said:
Posted 05/13/2010 at 1:14 AM
bad credit car loan said:

var query = from p in db.Products

join p2 in db.Categories on p.CategoryID equals p2.CategoryID

orderby p.ProductID ascending

select new { p.ProductID, p.ProductName, p.UnitPrice, p.CategoryID, p2.CategoryName };

I want a shorter way to select columns: ProductID, ProductName and UnitPrice because they are on the same table.

Is there a way to call that table and put it in the select statement?

Posted 05/13/2010 at 1:14 PM
migliore gioco al casinò online said:

I am using static Datacontext Variable. it works fine.. But sometime i got error on website, e.g. Datareader is already open.. then my website goes down for you say 4-5 minutes.. It works fine again..Is this due to connection pooling.Plese suggest me..

Posted 05/19/2010 at 2:17 AM
bad credit auto loan said:

Let's look at how the code was constructed. The from clause specifies the data source, in this case, the carNames collection. The where clause applies the filter, in this case, the list of all elements in the collection containing the letter 'e'

Posted 07/20/2010 at 9:28 PM
junk yards said:

project is to retrieve xml files from various sources and displaying them. this is to be provided as web service. here the user gives the query,and the query is to be decomposed using bottom up strategy.then the query is decomposed into sub queries according to the schema in which the data is present. each sub query is sent to respective schema or database. thus integrating those data and providing a single view to the user

Posted 07/29/2010 at 12:48 PM
darkit said:

thanks

Posted 08/20/2010 at 10:39 AM
coach outlet said:

coach outlet

Posted 08/26/2010 at 1:56 PM
louis vuitton bags said:

louis vuitton bags

Posted 08/26/2010 at 1:56 PM
coach outlet store online said:
Posted 08/26/2010 at 9:17 PM

Leave a Comment