Click here to Skip to main content
14,385,812 members

Playing Around with LINQ for JavaScript

Rate this:
5.00 (7 votes)
Please Sign up or sign in to vote.
5.00 (7 votes)
18 Jun 2015CPOL
Playing around with LINQ for JavaScript

One of the more awesome things I like about being a .NET developer is LINQ. LINQ (Language Integrated Query) is a fluent query interface implemented in the .NET framework. It helps you query, sort and order any type of collection. Below you’ll see an example how to sort an array with integers:

int[] numbers = new int[]{ 1, 9, 4, 6, 2, 9, 11, 31 };
int[] orderedNumbers = numbers.Order(i => i).ToArray();

This is a very neat way of querying arrays, lists, dictionaries, objects, etc. There is also a near complete implementation of Linq for JavaScript: https://linqjs.codeplex.com/. Playing with and testing out this library was on my list for a very long time. I’ve made 5 examples which run out of the box with Node.js (or io.js). You can also use the library for browser based JavaScript projects.

Example 1: Filtering by File Name

var linq = require("linq");
var fs = require("fs");
//Example 1

//Let's take a look at all the files in Windows' System32 folder
fs.readdir("C:\\Windows\\System32", function(err, files){
	if(err){
		//If there's an error, show it
		console.log(err);
	}
	else{
		//Well, we have an array with file names here. I only want to show all DLL files
		var result = linq.from(files)
					 .where(function(f){
					 	return f.substr(f.length - 3) == "dll"
					 })
					 .toArray();
		console.log(result);
	}
});

Console Output

[ 'accessibilitycpl.dll
  'ACCTRES.dll',       
  'acledit.dll',       
  'aclui.dll',         
  'acmigration.dll',   
  'acppage.dll',       
  'acproxy.dll',       
  'ActionCenter.dll',  
  'ActionCenterCPL.dll'
  'ActionQueue.dll',   
  'ActivationVdev.dll',
  'activeds.dll',      
  'actxprxy.dll',      
  'adhapi.dll',        
  'adhsvc.dll',        
  'AdmTmpl.dll',       
  'admwprox.dll',      
  'adprovider.dll',    
  'adrclient.dll',....

Example 2: Getting the Average and Highest and Lowest Number

var linq = require("linq");

//Example 2
var grades = [4.4, 8.2, 5.6, 7.8, 6.9, 5.0, 9.8, 10.0, 7.9];
//Ok, I have an array of grades, but I want to know the average:

var average = linq.from(grades)
			  .average();
console.log("Average grade: "+average);

//There, easy, right?

//But what's the lowest grade?
var lowestGrade = linq.from(grades)
				  .min();
console.log("Lowest grade: "+lowestGrade);

//And the highest?
var highestGrade = linq.from(grades)
				  .max();
console.log("Highest grade: "+highestGrade);

Console Output

Average grade: 7.28888888888889
Lowest grade: 4.4
Highest grade: 10

Example 3: Taking a Subset of an Array

var linq = require("linq");
//Let's say we have a large array of numbers

var arr = [];
for(var i=0;i<=1000;i++){
	arr.push(i);
}

//and we want 10 numbers from the 500th index. This is how it's done:
var result = linq.from(arr)
			 .skip(500)
			 .take(10)
			 .toArray();
console.log(result);

//Skip, like the name says, skips the first 500 numbers and take "takes" 
//the next 10 numbers from the array

Console Output

[ 500, 501, 502, 503, 504, 505, 506, 507, 508, 509 ]

Example 4: Joining 2 Arrays

var linq = require("linq");

//Let's say we have 2 arrays
var arr1 = ["a", "b"];
var arr2 = ["c", "d"];

//Let's combine these 2 arrays
var result = linq.from(arr1)
			 .concat(arr2)
			 .toArray();
console.log(result);

Console Output

[ 'a', 'b', 'c', 'd' ]

Example 5: Making a Selection Out of an Object Array

var linq = require("linq");

//We have an array with a few objects inside. We only want an array with all names.

var arr = [
	{name: "Duco", country: "Netherlands"},
	{name: "Bill", country: "USA"},
	{name: "Norbert", country: "Belgium"}
];

//We do it like this
var result = linq.from(arr)
			 .select(function(x){
			 	return x.name;
			 })
			 .toArray();
console.log(result);
//There

Console Output

[ 'Duco', 'Bill', 'Norbert' ]

I like this way of working with variables in both C# and JavaScript and I'm going to use it for future projects for sure. You can download the sample code here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 5 Pin
Baxter P24-Jun-15 11:18
professionalBaxter P24-Jun-15 11:18 
QuestionShow the results Pin
Sacha Barber18-Jun-15 21:37
mvaSacha Barber18-Jun-15 21:37 
AnswerRe: Show the results Pin
Duke Of Haren18-Jun-15 22:27
MemberDuke Of Haren18-Jun-15 22:27 
GeneralRe: Show the results Pin
Sacha Barber19-Jun-15 3:26
mvaSacha Barber19-Jun-15 3:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Technical Blog
Posted 18 Jun 2015

Stats

18.6K views
13 bookmarked