2017-06-06 46 views
0

我有下面的表达式从VB.NET转换为C#:转换VB.NET GROUP BY表达式到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部分...

+0

小鸡蛋里挑骨头,'和'应该是'AndAlso'。 '和'是按位和操作符,而不是逻辑和。 –

+0

@JeffMercado与一些LINQ提供者,你必须使用'And'或单独的'Where'查询,因为SQL没有任何短路的概念 –

+0

@JacobKrall,这是不相干的,这是操作符的错误用法这个背景并没有实际的效果。如果它是相关的,则查询提供者的工作是根据数据源的要求构建查询。 –

回答

2

逐字翻译是

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); 
+0

我想你的第一个查询将是正确的,如果只是删除了“g =(从g2中选择g2)”部分。 –

+0

我在删除推荐删除的部分后测试了第一个查询,它似乎完全重现了原始的VB行为。 –

+0

有趣 - 我需要根据LINQpad进行设置,因为在VB中,查询没有“Select”,而“Into g = Group”将“g”添加到“Array”结果中,而不是“ 'IGrouping'。 'g =(从g2中选择g2)'创建一个'IEnumerable'而不是'Array',但是在其他方面可以比较(通过LINQPad'Dump()方法)。 – NetMage

1

应一旦你掌握了语法,就很简单。你会做这样的事情

组“记载”由“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() } 
+1

一些排序肯定缺失 –

1

GroupBy后利用anonymous types,这将使gOrderBy组的Count()

.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.Keyd对象
  • g.Count指匿名类型的Count的d不是LINQ的Count()