Www
Www

Reputation: 442

What does the "aggregate list" do for LINQ group by clauses?

This page implies that I can do something like this:

From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)

And then be able to use the Sum of values later on. Perhaps in something like this (not actually working code):

From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where results.Sum >= 10
From result In results
Select result

This should select all things where the sum of values for things with the same name is greater than 10.

Through more testing, I can't get results to be anything other than the first item in a so called aggregate list. In other words the following are effectively identical as far as I can tell:

Group By thing.name Into results = Group, Sum(thing.value)

Group By thing.name Into results = Group

What is this aggregate list even supposed to do and how can I use it?

A side note: The example in the link seems to use Count instead Sum but actually uses two different definitions of Count and is worthless as an example.

Upvotes: 0

Views: 643

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134571

It helps to understand what exactly is happening when you perform a linq query.

When you do a group by in the query syntax, you're creating result objects with property names of the key and aggregates.

Your query:

From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)

Yields a collection of objects with properties:

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)

Once you understand that, you can do more filtering. To filter results where the sum is less than 10:

From thing In things
Group By thing.ID Into result = Group, Sum(thing.value)
Where Sum < 10

So to fix your other query, you would do this:

From thing In things
Group By thing.name Into results = Group, Sum(thing.value)
Where Sum >= 10
From result In results
Select result

Upvotes: 1

Related Questions