Sunday, April 21, 2013

Advantages of Linq C#

What is LINQ?

Skip to Advantages

Linq in .net enables developers to write code in a declarative format Consider the code below. Here what I am trying to do is, find all the numbers in the array "nums", where the number is less that 5. Then I want to order those numbers in ascending order. What is shown below is the traditional way of imperative programming.

int[] nums = { 5, 4, 3, 9, 8, 6, 7, 2, 0 };
int[] small=new int[nums.Length];
int y = 0;

int length = nums.Length;

for (int i = 0; i < length; i++)
    if (nums[i] < 5)

Array.Resize(ref small, y);


for (int i = 0; i < small.Length;i++ )

The output of the above code would be 0 2 3 4

If I were to write the same code using LINQ which is a declarative style of programming, this is how the code would look like this

int[] nums = { 5, 4, 3, 9, 8, 6, 7, 2, 0 };

var small = from n in nums where n < 5 orderby n select n;

foreach (var x in small)

As you can see above, in a declarative style of programming, you don't need to worry about how it gets done (aka the implementation) . You just tell the compiler, this is what you want and the compiler gets it done for you.

Whats explained above is a practical way to look at it. But strictly speaking LINQ is technology where you can define a provider for a datasource, which can then be used to make declarative LINQ statements to query that datasource. For example,  you can create your own provider that takes LINQ queries and converts it into commands for quering amazon through webservices.  That would be called a LINQ to Amazon provider.

These are the advantages of LINQ

  1. Its a declarative style of programming, hence the code is simpler and lesser.
  2. LINQ provides nearly identical syntax for querying many different data sources such as Collections, Objects, SQL Server, RavenDB etc. Hence you don't have to learn a new syntax for querying every different form of a datasource. You can just use LINQ everywhere.(Note LINQ to XML which is significantly different is an exception)
  3. LINQ provides an object oriented view of the data.
  4. Using LINQ you can take data from one datasource and put that data in another form of data source. For instance using LINQ you can take data from a SQL server and write it into XML with very less code. This property is called the transformative property of LINQ.

1 and 2 are the most important advantages of LINQ.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator