Retrieving data from different sources using Linq

By | 25 December, 2012

This used to be the classical pain in the ass. Let’s see what happens currently…

LINQ is an incredibly powerful component that Microsoft .NET has introduced during the last few years. In spite of having some basic knowledge about this tool since some years ago (during attending lessons in the Msc in Web Engineering that I took) it wasn’t until these last months when I have had the opportunity to work with it more deeply.

Apart from allowing developers to select data very easily from databases, it’s able to work with different sort of datasources. For instance, with LINQ you can get data from collections, arrays or even XML files with a similar sintax, which is usually used to work with databases.

So now you can use clauses like SELECT, WHERE, ANY, GROUP BY or FIRST combine with LAMBDA PREDICATES to get the data you want in a very clean and uniform way. No matter what the datasource is.

Here you are a simple sample of this, however notice that it’s using Integers but LINQ is compatible with complex objects or classes.

using System;
using System.Linq;

class Program
static void Main()
int[] array = { 1, 2, 3, 6, 7, 8 };
// Query expression.
var elements = from element in array
orderby element descending
where element > 2
select element;
// Enumerate.
foreach (var element in elements)
Console.Write(' ');

And the output would be:
8 7 6 3

In the query expression, we select all the elements from the array in descending order (high to low). We then filter out elements less than or equal to 2. In the foreach-loop, we evaluate the expression and print the results.

From my point of view, I find it extremely useful and maybe one of the best pieces of software that Microsoft has introduced in the las few years.

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.