【问题标题】:Converting a linq-query to linqjs将 linq 查询转换为 linqjs
【发布时间】:2016-06-20 11:40:08
【问题描述】:

现在通过将一些旧的 Linq-query 转换为 LinqJs-query 来尝试学习 LinQJS。

这是 Linq 查询。

(from y in class1
 join x in class2 on y.Id equals x.Name
 group y by new { y.Date, x.Number } into xy
 select new class3()
 {
 }).ToList();

这是我目前的尝试(已被多次重写)。我想我只是不太了解语法。

var example = Enumerable.from(this.class1)
    .join(
        this.class2,
        "y => y.Id",
        "x => x.Name",
        " "
    )
    .groupBy("x.Date", "y.Number")
    .select(xy= new Class3(), { })
    .ToArray();

【问题讨论】:

    标签: javascript linq linq.js


    【解决方案1】:

    好吧,你可以这样做

    首先是join部分。

    var res = Enumerable.From(class1)
             .Join(
                    class2,
                    "x => x.Id",
                    "y => y.Name",
                    //I flattened all to make things more readable, you could also choose (x, y) => {c1:x, c2:y} for example
                    "(x, y) => {dte:x.Date, id:x.Id, name:y.Name, nb:y.Number, val:y.val} "
    
                    ).ToArray();
    

    然后按部分分组(当然也可以全部合二为一)

            var res2 = Enumerable.From(res)
      .GroupBy("p => {Date:p.dte, Number:p.nb}",
               "p=> p",
               //that's the "select" part, so put what you need in it
               "(p, grouping) => {key: p, values: grouping.source}")                
      .ToArray();
    

    然后你可以选择你需要的。

    可悲的是,似乎(或者我不知道如何做到这一点)由多个字段组成的组不能正常工作(它返回多个记录)。

    虽然.GroupBy("p => p.dte}", 按预期工作。

    【讨论】:

      【解决方案2】:

      首先,重要的是要了解查询语法中的 linq 查询在转换为使用方法调用语法时是什么。

      (from y in class1
       join x in class2 on y.Id equals x.Name
       group y by new { y.Date, x.Number } into xy
       select new class3()
       {
       }).ToList();
      

      C# 等价物:

      class1.Join(class2, y => y.Id, x => x.Name, (y, x) => new { y, x })
          .GroupBy(z => new { z.y.Date, z.x.Number })
          .Select(xy => new class3())
          .ToList();
      

      那么它应该很容易转换为 Linq.js 等效项。

      var query =
          class1.Join(class2, "$.Id", "$.Name", "{ y: $, x: $$ }")
              .GroupBy(
                  "{ Date: $.y.Date, Number: $.x.Number }",
                  null,
                  null,
                  "$.Date + ' ' + $.Number"
              )
              .Select("new class3()")
              .ToArray();
      

      请注意,由于我们使用对象作为键,我们必须提供比较选择器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 2011-02-25
        相关资源
        最近更新 更多