Dot-Net

使用 GROUP BY 和 Count(*) 到匿名類型的 LINQ 查詢

  • August 17, 2018

我正在嘗試使用 LINQ 查詢來確定我擁有的每種特定對像類型的數量,並將這些值記錄到匿名類型中。

假設我有一些看起來像這樣的數據(確實有對象暴露了這個屬性,但它的工作原理是一樣的)

GroupId
1
1
2
2
2
3

我知道如何在 SQL 中格式化我的查詢。它會是這樣的:

SELECT grp = GroupId, cnt = COUNT(*)
FROM myTable
GROUP BY GroupId

在這種情況下,輸出將類似於SQL Fiddle

GroupID  Count
1        2
2        3
3        1

如何在 vb.net 中使用 LINQ 做同樣的事情

Dim groupCounts = From person In data
                 Group By person.GroupId
                 Select new {group = person.GroupId, count = count(*)}

這不太正確,但我認為它很接近。

另外,對匿名類型了解不多,我是否可以groupCounts提前聲明它將是每個具有 group 和 count 屬性的項目的列舉?

嘗試在 LinqPad 中使用它,並為您的數據庫實體替換它應該讓您更接近。

Public Sub grouper2()
   Dim numbers = New Integer() {1,1,2,2,2,3}

   Dim numberGroups = From w In numbers _
                   Group w By Key = w Into Group _
                   Select Number = Key, numbersCount = Group.Count()

   'linqpad specific output
   'numberGroups.Dump()

   For Each g In numberGroups
       Console.WriteLine("Numbers that match '{0}':", g.Number)
           Console.WriteLine(g.numbersCount)        
   Next

End Sub

我習慣了 C#:

var query = from person in data
           group person by person.GroupId into grouping
           select new { Key = grouping.Key, Count = grouping.Count() }

但我已經在 VB 中測試了以下程式碼段並且它有效:

Dim files = Directory.GetFiles (Path.GetTempPath()).Take (100).ToArray().AsQueryable()

Dim groups = From f In files Group f By key = Path.GetExtension (f) Into Group
            Select Key = key, NumberGroup = Group.Count()

引用自:https://stackoverflow.com/questions/16489405