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");
fs.readdir("C:\\Windows\\System32", function(err, files){
if(err){
console.log(err);
}
else{
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");
var grades = [4.4, 8.2, 5.6, 7.8, 6.9, 5.0, 9.8, 10.0, 7.9];
var average = linq.from(grades)
.average();
console.log("Average grade: "+average);
var lowestGrade = linq.from(grades)
.min();
console.log("Lowest grade: "+lowestGrade);
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");
var arr = [];
for(var i=0;i<=1000;i++){
arr.push(i);
}
var result = linq.from(arr)
.skip(500)
.take(10)
.toArray();
console.log(result);
Console Output
[ 500, 501, 502, 503, 504, 505, 506, 507, 508, 509 ]
Example 4: Joining 2 Arrays
var linq = require("linq");
var arr1 = ["a", "b"];
var arr2 = ["c", "d"];
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");
var arr = [
{name: "Duco", country: "Netherlands"},
{name: "Bill", country: "USA"},
{name: "Norbert", country: "Belgium"}
];
var result = linq.from(arr)
.select(function(x){
return x.name;
})
.toArray();
console.log(result);
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.
CodeProject