Fabrice's weblog

Tools and Source

News

My .NET Toolbox
An error occured. See the script errors signaled by your web browser.
No tools selected yet
.NET tools by SharpToolbox.com

Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

Tuneo

ASP.NET Hosting transatlantys

Contact

Me

Others

Selected content

Archives

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

Comments

Nikhil Kothari said:

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 :-)

# December 29, 2006 2:03 AM

Andrey Skvortsov said:

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

# December 30, 2006 11:17 AM

Simon said:

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.

# January 1, 2007 9:14 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)