use linq and lamdba in javascript
npm install linq-js
$ npm install --save linq-js
`
`javascript
const Enumerable = require('linq-js');
`
> * description:This module require ES6. I suggest you to use this with ES6. The following examples is already use ES6.
> * 说明:本module依赖于ES6。建议项目在中使用ES6。以下案例中将均使用ES6写法。
$3
`typescript
interface IEnumerable { };
function asEnumerable():IEnumerable;
//You can use the asEnumerable methods of every object's to get an IEnumerable object;
//任何对象都有asEnumerable方法用来获取IEnumerable对象
`
> e.g. 案例
> `javascript
> 'abc'.asEnumerable();
> [1,2,3].asEnumerable();
> ({a:1,b:2}).asEnumerable();
> `
$3
> e.g. 案例 简单的判断数组中的数据
> `javascript
> let pets = [ { name: "Barley", age: 8, vaccinated: true }, { name: "Boots", age: 4, vaccinated: false }, { name: "Whiskers", age: 1, vaccinated: false } ];
> let unvaccinated = pets.asEnumerable().any(p => p.age > 1 && p.vaccinated === false);
> console.log(There ${ unvaccinated ? "are" : "are not any" } unvaccinated animals over age one.);
> // This code produces the following output: 这段代码输出以下内容:
> // There are unvaccinated animals over age one.
> `
> e.g. 案例 两个数组进行内连接查询
> `javascript
> let magnus = { id: 1, name: "Hedlund, Magnus" }, terry = { id: 2, name: "Adams, Terry" }, charlotte = { id: 3, name: "Weiss, Charlotte" };
> let barley = { name: "Barley", owner: 2 }, boots = { name: "Boots", owner: 2 }, whiskers = { name: "Whiskers", owner: 3 }, daisy = { name: "Daisy", owner: 1 };
> let people = [ magnus, terry, charlotte ];
> let pets = [ barley, boots, whiskers, daisy ];
> let query = people.asEnumerable().join(pets,
> (person, pet) => ({ ownerName: person.name, pet: pet.name }),
> person => person.id,
> pet => pet.owner);
> for (let obj of query) {
> console.log(${ obj.ownerName } - ${ obj.pet });
> }
> /*
> This code produces the following output: 这段代码输出以下内容:
> Hedlund, Magnus - Daisy
> Adams, Terry - Barley
> Adams, Terry - Boots
> Weiss, Charlotte - Whiskers
> */
> ``