使用GROUP BY和Count(*)将LINQ查询转换为匿名类型 [英] LINQ query with GROUP BY and Count(*) into Anonymous Type

查看:175
本文介绍了使用GROUP BY和Count(*)将LINQ查询转换为匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用LINQ查询来确定每个特定对象类型的数量,并将这些值记录到匿名类型中。



假设我有一些看起来像这样的数据(实际上有暴露这个属性的对象,但它的工作原理是一样的)。

pre $ Group $ $ $ b b 1 b b b 1 b b 2 b b 2 b b 2 b b 3 b b b b b

我知道如何在SQL中格式化查询。它会是这样的:
$ b

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

在这种情况下,输出可能类似于这个

  GroupID Count 
1 2
2 3
3 1

如何在vb.net中使用LINQ做同样的事情
$ b

  Dim groupCounts =从人在数据
Group By person.GroupId
选择新的{group = person.GroupId,count = count(*)}

这并不完全正确,但我认为它很接近。

另外,由于不了解匿名类型,我可以提前宣布 groupCounts 它是一个枚举项,每个项都有一个组a nd count属性?

解决方案

尝试在LinqPad中使用它,并为您的数据库实体创建它应该让您更靠近。



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

Dim numberGroups =从w在数字中_
Group w By Key = w进入Group _
选择Number = Key,numbersCount = Group.Count()

'linqpad特定输出
'numberGroups.Dump()

For Each g In numberGroups
Console.WriteLine(匹配'{0}'的数字' :,g.Number)
Console.WriteLine(g.numbersCount)
Next

End Sub


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:

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?

解决方案

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

这篇关于使用GROUP BY和Count(*)将LINQ查询转换为匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆