LINQ for JavaScript

LINQ is one of my favorite features in the C# language so far. There is no such a thing as filtering, ordering and grouping data using an easy and fluent API. In the last weeks I found myself writing lot of JavaScript code. More than just ajax calls, DOM manipulation and fancy animations, my team and I maintain a huge js model which includes entities, controllers and repositories. Because of that, many of the operations that we regularly implement in server-side are implemented in client-side as well such as finding, sorting and grouping elements in data collections. On the server we use LINQ to perform such operations, but how to implement them in JavaScript?

Luckly, there is a JavaScript library that provides all LINQ operations with a very similar sintaxe. Just as C#, LINQ for JavaScript operates under IEnumerable objects. Therefore, the first thing to do is create an IEnumarable object with the FROM function. To illustrate the library usage, I will start with an array of people. The code below includes the Person object definition and the creation of an enumerable of people from an array. Very straightforward.

init-person

Since the enumerable is created, we are free to perform all LINQ operation on it. Let’s start with a simple search: I want to find the person whose name is ‘Fernando’. The code below illustrates that. Notice the sintaxt used by the library. While in C# we write lambda expressions (x => x.Name), here we use the symbol $.

first

Next, we filter the collection with the people with age greater then 25 and select their names.

where

Next, we order the collection by age and select their names.

order

Finally, we group the collection by sex. In addition, each group is ordered by name.

groupBy

As you can see, there is no secret. The sintaxe is really really similiar. I could show others the operations here, but they are all avaible in the library’s documentation. So, if you got interested by LINQ for JavaScript, take a look in the project page on codeplex. It helped me a lot and hope it can bu useful for you as well.

See you,
Fernando

Leave a comment