Reputation: 29987
I'm trying to use a LINQ query to determine how many of each particular object type I have and record those values into an anonymous type.
Let's say I have some data that looks like this (there are really objects exposing this property, but it'll work the same)
GroupId
1
1
2
2
2
3
I know how to format my query in SQL. It would be something like this:
SELECT grp = GroupId, cnt = COUNT(*)
FROM myTable
GROUP BY GroupId
In this case the output would be something like this SQL Fiddle:
GroupID Count
1 2
2 3
3 1
How can I do the same thing with LINQ in vb.net
Dim groupCounts = From person In data
Group By person.GroupId
Select new {group = person.GroupId, count = count(*)}
That's not quite right, but I think it's close.
Also, not knowing much about anonymous types, can I actually declare groupCounts
ahead of time that it will be an enumeration of items which each have a group and count property?
Upvotes: 7
Views: 39986
Reputation: 336
I'm used to C#:
var query = from person in data
group person by person.GroupId into grouping
select new { Key = grouping.Key, Count = grouping.Count() }
But I have tested the following snippet in VB and it works:
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()
Upvotes: 16
Reputation: 1196
Try using this in LinqPad, and subbing out for your database entity it should get you closer.
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
Upvotes: 7
Reputation: 29987
So vb is a bit odd when it comes to translating this syntax. It seems that you can only insert groups into
an element titled exactly "Group
". This then exposes the rest of the grouping functionality
From person In data
Group person By grpId = person.GroupId Into Group
Select id = grpId, count = Group.Count
Upvotes: 2