【问题标题】:Convert VB.NET Group By expression to C#将 VB.NET Group By 表达式转换为 C#
【发布时间】:2017-06-06 20:44:30
【问题描述】:

我必须将以下表达式从 VB.NET 转换为 C#:

Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending

我对 Group By 部分感到困惑...

【问题讨论】:

  • 次要的挑剔,And 应该是AndAlsoAnd 是位与运算符,而不是逻辑与。
  • @JeffMercado 与一些 LINQ 提供程序,您必须使用 And 或单独的 Where 查询,因为 SQL 没有任何短路的概念
  • @JacobKrall,这无关紧要,这是在这种情况下错误地使用了运算符并且没有实际效果。 如果它是相关的,那么查询提供者的工作就是根据数据源的要求构建查询。
  • 如果您编译您的 VB 程序,然后使用 dotPeek 或 Reflector 反编译为 C# - 它显示的代码是什么?
  • @JeffMercado 这实际上是错误的。并且是 both 逻辑联合和按位运算符。 AndAlso 是 short-circuited 联合运算符。为了使 AndAlso 工作,提供者必须实现它。虽然他们可能已经这样做了,但有可能获得一个不实现所有运算符的提供程序。但总的来说,两者都是安全的,如果提供商支持短路,最好使用 AndAlso。如果不支持短路,但实现了操作符,执行上没有区别。

标签: c# vb.net linq group-by


【解决方案1】:

直译是

var z = from d in db.GPSdevice
        where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
        orderby d.ListOrder descending
        group d by d.GeofenceLocation into g
        orderby g.Count() descending
        select new { Geofence = g.Key, g = (from g2 in g select g2), Count = g.Count() };

但这不会产生与原始 VB 查询完全相同的类型。

这是一个更(过早?)优化的版本,它确实会产生相同的类型:

var z2 = (from d in db.GPSdevice
         where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
         group d by d.GeofenceLocation into g
         select new { Geofence = g.Key, g = (from g2 in g orderby g2.ListOrder descending select g2).ToArray(), Count = g.Count() }).OrderByDescending(g => g.Count);

【讨论】:

  • 我认为您的第一个查询如果只是删除“g = (from g2 in g select g2)”部分是正确的。
  • 我在删除我建议删除的部分后测试了第一个查询,它似乎完全重现了原始 VB 行为。
  • 有趣 - 我需要根据 LINQpad 将其放入,因为在 VB 中,查询没有Select,而Into g = Groupg 添加到@987654326 的结果中@ 而不是IGroupingg = (from g2 in g select g2) 创建 IEnumerable 而不是 Array,但在其他方面具有可比性(通过 LINQPad Dump() 方法)。
【解决方案2】:

一旦你掌握了语法,应该会很直接。你会做类似的事情

按“records.property”将“记录”分组到 grouped_set

然后您将执行选择以执行获取您的密钥(按属性分组)和相关计数。您的 linq 语句应如下所示:

from d in db.GPSdevice
where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
group d by d.GeofenceLocation into g 
select new { GeofenceLocation = g.Key, Count = g.Count() }

【讨论】:

  • 某些排序肯定丢失了
【解决方案3】:

在您的GroupBy 之后使用anonymous types,这将允许您将OrderBy 分组gCount()

.Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })

使用 LINQ 流畅的语法:

var z = db.GPSdevice
          .Where(d => d.CompanyId == currentuser.CompanyId && d.Type == "Trailer")
          .OrderByDescending(d => d.ListOrder)
          .GroupBy(g => g.GeofenceLocation)
          .Select(g => new { Group = g.Key.GeofenceLocation, Count = g.Count() })
          .OrderByDescending(g => g.Count)

注意:

  • g.Key 指的是d 对象
  • g.Count 是指匿名类型的 Count 而不是 LINQ 的 Count()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2019-09-28
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多