ASP.NET Hosting

LINQ to Objects for JavaScript

Nikhil Kothari, whose blog you should visit immediately if you're doing web development, demonstrates how to reproduce LINQ to Objects in JavaScript.

Nikhil is an architect on the Web Platform and Tools team at Microsoft known for his great projects, past and present, which include: ASP.NET Web Matrix, Web Development Helper, and Script#.

This time, Nikhil has a post in which he demonstrates how it's possible to write queries against JavaScript arrays, similarly to what LINQ to Objects offers for C# and VB.NET.

The following LINQ query in C#:

var someLocations =
  from location in allLocations
  where location.City.Length > 6
  select new { City = location.City, Country = location.Country };

can also be written as follows using query operators:

var someLocations =
 
allLocations
    .Where(
location => location.City.Length > 6)
    .Select(location => new { City = location.City, Country = location.Country });

The equivalent query could be written in JavaScript as follows: 

var someLocations =
  allLocations
    .filter(function(location) { return location.City.length > 6; })
    .map(function(location) { return { City: location.City, Country: location.Country }; });

Pretty close, isn't it? Learn more...


Cross-posted from http://linqinaction.net

3 Comments

  • The middle code snippet, i.e. the version without LINQ syntax that instead uses the underlying extension methods, adds a nice touch to demonstrate the parallels.

    Also, thanks for the link :-)

  • That's not LINQ for javascript but script# for javascript,title is misleading.

  • Many new features of C# since version 2.0 seem to be inspired from Javascript : Anonymous methods (and their behavior with local variables), extension methods, and the orientation of Linq (passing "funclets" as parameters everywhere) are very close to what we do with Javascript.

Comments have been disabled for this content.