2013-05-10 119 views
6

我试图使用LINQ查询来确定每个特定对象类型的数量,并将这些值记录到匿名类型中。LINQ查询与GROUP BY和计数(*)转换为匿名类型

比方说,我有一些数据,看起来像这样(真的有对象暴露此属性,但它会工作相同)

GroupId 
1 
1 
2 
2 
2 
3 

我知道如何格式化我的SQL查询。这将是这样的:

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

在这种情况下,输出会是这样的this

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提前宣布它将是一个枚举的项目,每个项目都有一个组和计数属性?

回答

7

尝试在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 
14

我已经习惯了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() 
2

所以VB是有点古怪,当涉及到翻译此句法。看起来你只能插入标题为“Group”的元素into。这就暴露了分组功能

From person In data 
Group person By grpId = person.GroupId Into Group 
Select id = grpId, count = Group.Count