March 23, 2013

Linq, Now in Javascript flavor

While this library is a couple of years old now, it is still a pretty awesome library to mention for javascript. The main reason is the fact that if you’re a .net developer, then you know Linq is an awesome tool to use for querying objects.

So, I was using this with node.js and had to make a small tweak to get it to work. Below is an example what I did:

 exports.Enumerable = function(){ ... }(); 

This allows the javascript file to be imported into a node javascript file like so:

 var Enumerable = require('./linq.min.js').Enumerable; 

Now that we got that out of the way, let’s set up some data:

 var category = [ { "Id": 1, "Name": "Node.js" }, { "Id": 2, "Name": "HTML" }, { "Id": 3, "Name": "General" }, { "Id": 4, "Name": "C#" } ]; var article = [ { "Title": "Super Awesome Blog", "CategoryId": category[0].Id, "Post": "myPost" }, { "Title": "Making Linq", "CategoryId": category[1].Id, "Post": "yourPost" }, { "Title": "Using Node.js", "CategoryId": category[2].Id, "Post": "OnePost" }, { "Title": "HTML 5 awesomeness", "CategoryId": category[3].Id, "Post": "TwoPost" }, { "Title": "Random Title Name", "CategoryId": category[0].Id, "Post": "ThreePost" } ]; 

Here I created some sample data that looks like 2 tables, an article table, which is connected to also, the category table. We will use these 2 tables to do some queries. Let’s check out this join:

 var queryResult = Enumerable.From(category) .Join(article, function (cat) { return cat.Id; }, function (art) { return art.CategoryId }, function (cat, art) { return { CategoryName: cat.Name, ArticleTitle: art.Title } }) .OrderByDescending(function (x) { x.CategoryName; }) .ToArray(); 

This may look a little different from a .net query, that’s because instead of anonymous Lambdas in C sharp, we have to use anonymous functions of javascript. As you look at the query though, you will notice it makes sense. Join still takes another collection, and 3 lambdas, 2 for which columns to join on, and 1 to show how to join the 2 tables together.

You might also notice Enumerable.From. Let’s just say that this is a way to allow us to do the yielding that Enumerable collections do in Linq, allowing lazy loading. Along with using an enumerable, we also can return the data in an array, dictionary and lookup, just like linq would allow. Let’s see the output:

 for (var i = 0; i < queryResult.length; i++) { console.log('Category: "'+queryResult[i].CategoryName+'" Title: "'+queryResult[i].ArticleTitle+'"'); } 

And we can use the results from the query as if it was a normal javascript array object. If you want more information on the linq library, check out this link: http://linqjs.codeplex.com/