我必须将以下表达式从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部分感到困惑......
答案 0 :(得分: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);
答案 1 :(得分:1)
一旦掌握了语法,就应该非常直接。你会做类似
的事情将“records.property”的“记录”分组到groups_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() }
答案 2 :(得分:1)
在GroupBy
之后使用anonymous types,这样您就可以OrderBy
群组g
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.Key
引用d
对象g.Count
是指匿名类型的Count
,而不是LINQ' Count()
。