0

我已经尝试了几个小时来使用 json.js 来做到这一点,但对于看似简单的事情来说太过分了。我有这个示例数据:

    var hotels = [
        { id: 101, Name: "Hotel 101", WebFacilities: [8, 9, 10] },
        { id: 102, Name: "Hotel 101", WebFacilities: [8] },
        { id: 103, Name: "Hotel 101", WebFacilities: [8, 10] }
    ];

    var facilities = [
        { id: 8, Name: "Facility 8" },
        { id: 9, Name: "Facility 9" },
        { id: 10, Name: "Facility 10" }
    ];

我想得到这个:

    var selectedFacilities = [
        { id: 8, Name: "Facility 8", Count: 3 },
        { id: 9, Name: "Facility 9", Count: 1 },
        { id: 10, Name: "Facility 10", Count: 2 }
    ];

我该怎么做呢?

4

2 回答 2

2

因此,您似乎正在尝试计算每个设施的数量。

这是使用 C# 编写查询的一种方法:

var hotelFacilities =
    from hotel in hotels
    from id in hotel.WebFacilities
    group id by id;

var query =
    from facility in facilities
    join g in hotelFacilities on facility.id equals g.Key
    select new
    {
        id = facility.id,
        Name = facility.Name,
        Count = g.Count(),
    };

现在,如果您可以使用方法语法来描绘这一点,那么它几乎是对 linq.js 版本的 1:1 转换。

请注意,编译器翻译上述内容的方式通常会将GroupBy()调用包含在前一个SelectMany()调用中。然而,以这种方式编写将使编写 linq.js 等效查询更容易且不那么尴尬。

var hotelFacilities = hotels
    .SelectMany(hotel => hotel.WebFacilities)
    .GroupBy(id => id);

var query = facilities
    .Join(
        hotelFacilities,
        facility => facility.id,
        g => g.Key,
        (facility, g) => new
        {
            id = facility.id,
            Name = facility.Name,
            Count = g.Count(),
        }
    );

和等效的 linq.js 查询。

var hotelFacilities = Enumerable.From(hotels)
    .SelectMany("hotel => hotel.WebFacilities")
    .GroupBy("id => id")
    .ToArray();

var query = Enumerable.From(facilities)
    .Join(
        hotelFacilities,
        "facility => facility.id",
        "g => g.Key()",
        "(facility, g) => { id: facility.id, Name: facility.Name, Count: g.Count() }"
    ).ToArray();
于 2013-02-28T09:11:56.010 回答
0

用这个:

var selectedFacilities = facilities;

for(var i = 0; i < facilities.length; i++) {
    for(var j = 0; j < hotels.length; j++) {
        if(hotels[j]["id"] == facilities[i]["id"]) {
            // Add data
            selectedFacilities[i]["Count"] = hotels[i]["WebFacilities"].length;
        } else {
            selectedFacilities[i]["Count"] = 0;
        }
    }

}
于 2013-02-23T18:25:00.083 回答