Linq.js is a JavaScript library that allows you to manage collections easily and efficiently, mimicking the programming style of the popular LINQ (Language Integrated Query) library from .NET.
The LINQ.js library provides an API similar to that of LINQ in .NET, allowing us to perform complex queries on data collections using a fluent and expressive syntax.
LINQ.js is written in pure JavaScript and has no external dependencies, making it a lightweight and accessible option to add query functionality to our JavaScript applications.
For more information and detailed examples, we can check the project page on GitHub. There, we will find additional documentation and examples that can help us make the most out of this library in our developments.
Installation and Configuration
Installation in Node.js
To install LINQ.js in a Node.js project, we can use npm.
npm install linq
Then, we import it into our JavaScript code using the ES modules import syntax:
import Enumerable from 'linq';
let result = Enumerable.range(1, 10).where(i => i % 3 == 0).select(i => i * 10);
console.log(result.toArray()); // [30, 60, 90]
For this code to work, we must ensure that our project is configured to use ES modules. This is done by adding "type": "module"
in the package.json
file.
Installation in the Browser
To use LINQ.js in the browser, we can include the minified version of the library directly in our HTML:
<script type="module" src="./linq.min.js"></script>
<script type="module">
import Enumerable from './linq.min.js';
Enumerable.from([1, 2, 3]).forEach(x => console.log(x));
</script>
The library can also be loaded from a CDN.
How to Use LINQ.js
Filtering and Transforming Data
In this example, we filter a sequence of numbers to get only those divisible by 3 and then multiply them by 10:
import Enumerable from 'linq';
let result = Enumerable.range(1, 10)
.where(i => i % 3 == 0)
.select(i => i * 10);
console.log(result.toArray()); // [30, 60, 90]
Using Anonymous Functions
We can use anonymous functions (also known as lambda functions) to define our queries concisely:
import Enumerable from 'linq';
let result = Enumerable.range(1, 10)
.where(i => i % 3 == 0)
.select(i => ({ value: i, index: i * 10 }));
console.log(result.toArray()); // [{ value: 3, index: 30 }, { value: 6, index: 60 }, { value: 9, index: 90 }]
Working with Objects
LINQ.js also allows us to work with objects and perform complex queries on them. For example, we can transform an array of objects to include the index of each element:
import Enumerable from 'linq';
let array = ['apple', 'banana', 'cherry'];
let result = Enumerable.from(array)
.select((val, i) => ({ fruit: val, index: i }));
console.log(result.toArray()); // [{ fruit: 'apple', index: 0 }, { fruit: 'banana', index: 1 }, { fruit: 'cherry', index: 2 }]