"aggregate list" 对 LINQ group by 子句有何作用?
What does the "aggregate list" do for LINQ group by clauses?
This 页面暗示我可以做这样的事情:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
然后可以在以后使用 Sum
的值。也许是这样的(实际上不是工作代码):
From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where results.Sum >= 10
From result In results
Select result
这应该 select 所有 thing
具有相同名称的 thing
值的总和大于 10。
通过更多测试,我无法让 results
成为所谓聚合列表中第一项以外的任何内容。换句话说,据我所知,以下内容实际上是相同的:
Group By thing.name Into results = Group, Sum(thing.value)
Group By thing.name Into results = Group
这个聚合列表应该做什么,我该如何使用它?
旁注:link 中的示例似乎使用 Count
而不是 Sum
但实际上使用了 Count
的两种不同定义并且作为示例毫无价值.
这有助于理解执行 linq 查询时到底发生了什么。
当您在查询语法中进行分组时,您将创建具有 属性 键和聚合名称的结果对象。
您的查询:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
生成具有以下属性的对象集合:
ID
- the key (implicitly taken from the ID
property)
result
- a collection of items that is in the group (explicit alias to Group
)
Sum
- the sum of adding the value
of the items (implicitly taken from the aggregate name)
一旦你明白了这一点,你就可以做更多的过滤。筛选总和小于 10 的结果:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
Where Sum < 10
因此,要修复您的其他查询,您可以这样做:
From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where Sum >= 10
From result In results
Select result
This 页面暗示我可以做这样的事情:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
然后可以在以后使用 Sum
的值。也许是这样的(实际上不是工作代码):
From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where results.Sum >= 10
From result In results
Select result
这应该 select 所有 thing
具有相同名称的 thing
值的总和大于 10。
通过更多测试,我无法让 results
成为所谓聚合列表中第一项以外的任何内容。换句话说,据我所知,以下内容实际上是相同的:
Group By thing.name Into results = Group, Sum(thing.value)
Group By thing.name Into results = Group
这个聚合列表应该做什么,我该如何使用它?
旁注:link 中的示例似乎使用 Count
而不是 Sum
但实际上使用了 Count
的两种不同定义并且作为示例毫无价值.
这有助于理解执行 linq 查询时到底发生了什么。
当您在查询语法中进行分组时,您将创建具有 属性 键和聚合名称的结果对象。
您的查询:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
生成具有以下属性的对象集合:
ID
- the key (implicitly taken from theID
property)
result
- a collection of items that is in the group (explicit alias toGroup
)
Sum
- the sum of adding thevalue
of the items (implicitly taken from the aggregate name)
一旦你明白了这一点,你就可以做更多的过滤。筛选总和小于 10 的结果:
From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
Where Sum < 10
因此,要修复您的其他查询,您可以这样做:
From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where Sum >= 10
From result In results
Select result