Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query with GROUP BY and Count(*) into Anonymous Type

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?

like image 409
KyleMit Avatar asked May 10 '13 19:05

KyleMit


2 Answers

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()
like image 65
Salomonder Avatar answered Sep 28 '22 05:09

Salomonder


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
like image 28
crackhaus Avatar answered Sep 28 '22 04:09

crackhaus