Language Integrated Query (LINQ): Part 2

This is second part of the "LINQ" series of articles that I have started. And in this article, you will see some quick examples on LINQ title.


As I said in previous article, with LINQ you just need to perform three distinct actions: Obtain the Data Source, create the query and execute the query. You will see in sample programs given below. We will create Console Apps and test various LINQ concepts. I will walk through very simple programs here and in subsequent parts will dig in depth.


LINQ has the great ability to query on any source of data that could be collections of objects (in-memory data, like an array), SQL Database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.


LINQ to Array


Let's look at a Program to find Even Numbers using LINQ to Array.


Linq-to-array.jpg

 

If you execute the above program, you will get "2 4 6 8 10" as the output. You will notice 3 actions above, these actions will be changed always depending upon our project requirements. In the above example, the "data source" was an array that implicitly supports the generic IEnumerable<T> interface.


LINQ to XML


Now, let's move on to take a look at a LINQ to XML example and find student names from a XML file. LINQ to XML loads an XML document into a query-able XElement type and then IEnumerable<XElement> loads the query results, and using a foreach loop, we access it.


Student.XML File

 

linq-to-xml.jpg


linq-to-xml1.jpg

 

output-linq-to-xml.jpg
 

LINQ to SQL


In LINQ to SQL, we first create an object-relational mapping at design time either manually or by using the Object Relational Designer. Then, we write queries against the objects, and at run-time LINQ to SQL handles the communication with the database.


Now, let's look at the sample program.


 

linq-to-sql.jpg


output-linq-to-sql.jpg

 

Very simple examples on LINQ so far, stay tuned, you will find more stuff.


Similar Articles