LINQ (Language Integrated Query) - Part 2

This is second part of the ‘LINQ’ series posts that I have started from here. And in this post, you will see some quick examples on LINQ title.

As I said in previous post, with LINQ you just need to perform three distinct actions: Obtain the Data Source, Create the query and Execute the query, you will notice it 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 coming part will dig in depth.

LINQ has a great power of querying on any source of data that could be the collections of objects (in memory data, like 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 Number using LINQ to Array.

If you execute above program, you will get ‘2 4 6 8 10’ as output. You will notice 3 actions above, these actions will be changed always depending upon our project requirement. In above example, ‘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 LINQ to XML example and find student names from XML file. LINQ to XML loads an XML document into a query-able XElement type and then IEnumerable<XElement> loads the query result and using foreach loop we access it.

Student.xml File





LINQ to SQL:

In LINQ to SQL, we firstly 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.



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

Comments

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples