linq.js的用法

时间:2023-08-06 21:27:44

linq.js 详细介绍

linq.js 是一个 JavaScript 实现的 LINQ。

主要特性:

实现所有 .NET 4.0 的方法

complete lazy evaluation

full IntelliSense support for VisualStudio

two versions - linq.js and jquery.linq.js (jQuery plugin)

support Windows Script Host

binding for Reactive Extensions for JavaScript(RxJS) and IntelliSense Generator -> see documentation

NuGet install support

示例代码:

var jsonArray = [

{ "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },

{ "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },

{ "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },

{ "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }

]

// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]

var queryResult = Enumerable.From(jsonArray)

.Where(function (x) { return x.user.id < 200 })

.OrderBy(function (x) { return x.user.screen_name })

.Select(function (x) { return x.user.screen_name + ':' + x.text })

.ToArray();

// shortcut! string lambda selector

var queryResult2 = Enumerable.From(jsonArray)

.Where("$.user.id < 200")

.OrderBy("$www.cnzhaotai.com/ .user.screen_name")

.Select("$.user.screen_name + ':' + $.text")

.ToArray();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

用途:方便js操作查询json数据。

下载网址:http://jslinq.codeplex.com/

使用方法:只需要引用linq.js即可。

查询方法:

一、where查询

var myList = [

{ Name: "Jim", www.wanmeiyuele.cn Age: 20 },

{ Name: "Kate", www.leyouzaixan.cn  Age: 21 },

{ Name: "Lilei", Age: 18 },

{ Name: "John", Age: 14 },

{ Name: "LinTao", www.yszx11.cn/  Age: 25 }

];

var arrRes = Enumerable.From(myList).Where("x=>x.Name=='Jim'").ToArray();

二、排序:OrderBy

var myList = [

{ Name: "Jim",www.baohuayule.com  Age: 20 },

{ Name: "Kate", Age: 21 },

{ Name: "Lilei",www.baohuayule.cn  Age: 18 },

{ Name: "John", Age: 14 },

{ Name: "LinTao",www.006665.cn  Age: 25 }

];

var arrRes = Enumerable.From(myList).OrderBy("x=>x.Age").ToArray();//降序OrderByDescending()

三、去重:Distinct

var myList = [

{ Name: "Jim", Age: 20 },

{ Name: "Kate", Age: 20 },

{ Name: "Lilei", Age: 20 },

{ Name: "John", Age: 14 },

{ Name: "LinTao", Age: 25 }

];

var arrRes = Enumerable.From(myList).Distinct("x=>x.Age").ToArray();

四、遍历:ForEach

var myList = [

{ Name: "Jim", Age: 20 },

{ Name: "Kate", Age: 20 },

{ Name: "Lilei", Age: 20 },

{ Name: "John", Age: 14 },

{ Name: "LinTao", Age: 25 }

];

Enumerable.From(myList).ForEach(function(value, index){

document.write("值="+value+",索引="+index);

});

五、取唯一对象:First、FirstOrDefault、Last、LastOrDefault、Single、SingleOrDefault

var myList = [

{ Name: "Jim", Age: 20 },

{ Name: "Kate", Age: 20 },

{ Name: "Lilei", Age: 20 },

{ Name: "John", Age: 14 },

{ Name: "LinTao", Age: 25 }

];

var arrRes = Enumerable.From(myList).FirstOrDefault("x=>x.Age>18");

 

六、Skip、Take

Enumerable.Range(1,10).Skip(5)//结果[6,7,8,9,10]

Enumerable.Range(1,10).Take(5)//结果[1,2,3,4,5]