2017-06-06 86 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()