.net 使用 GROUP BY 和 Count(*) 将 LINQ 查询为匿名类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16489405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ query with GROUP BY and Count(*) into Anonymous Type
提问by KyleMit
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.
我正在尝试使用 LINQ 查询来确定我拥有的每个特定对象类型的数量,并将这些值记录到匿名类型中。
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:
我知道如何在 SQL 中格式化我的查询。它会是这样的:
SELECT grp = GroupId, cnt = COUNT(*)
FROM myTable
GROUP BY GroupId
In this case the output would be something like this SQL Fiddle:
在这种情况下,输出将类似于SQL Fiddle:
GroupID Count
1 2
2 3
3 1
How can I do the same thing with LINQ in vb.net
如何在 vb.net 中用 LINQ 做同样的事情
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 groupCountsahead of time that it will be an enumeration of items which each have a group and count property?
另外,对匿名类型了解不多,我实际上可以groupCounts提前声明它将是一个项目的枚举,每个项目都有一个 group 和 count 属性吗?
回答by Salomonder
I'm used to C#:
我习惯了 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:
但是我已经在 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()
回答by crackhaus
Try using this in LinqPad, and subbing out for your database entity it should get you closer.
尝试在 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
回答by KyleMit
So vb is a bit odd when it comes to translating this syntax. It seems that you can only insert groups intoan element titled exactly "Group". This then exposes the rest of the grouping functionality
所以 vb 在翻译这个语法时有点奇怪。似乎您只能插入into一个名为“ Group”的元素组。这将暴露其余的分组功能
From person In data
Group person By grpId = person.GroupId Into Group
Select id = grpId, count = Group.Count

