Reputation: 3012
I am curious what the x is for in a a linq group by clause: group x by ...
The x can be replaced by an 1:
var query = from box in c.Boxes
join item in c.Items on box equals item.Box
group 1 by new { BoxId = box.BoxId, item.ItemType.ItemTypeId } into g
select new { g.Key.BoxId, g.Key.ItemTypeId, Count = g.Count() };
Does anybody have a sample where the x (or wathever local variable you chose in the group by ) is really of some value?
I mean
var query2 = from box in c.Boxes
group box by box.BoxId into q
select q.Key;
can be replaced by
var query2 = from box in c.Boxes
group 1 by box.BoxId into q
select q.Key;
Upvotes: 2
Views: 161
Reputation: 9467
In group x by... the x is what gets aggregated.
So you could write something like
var childrenByAge = from child in class
group getName(child) by child.Age;
This gives you a grouping containing names of children for each age.
Here is a simple example where you can test the difference easily:
static void Main(string[] args)
{
var grouping = from c in "Hello World!"
group c by c; // Replace 'group c by' with 'group 1 by'
// and compare results
foreach (var group in grouping)
{
Console.Write("KEY: {0} VALUES :", group.Key);
foreach (var value in group)
Console.Write(" {0}", value);
Console.WriteLine();
}
Console.ReadKey();
}
Upvotes: 1
Reputation: 40516
That's the expression that determines what will go in the output of the group by
clause.
You are actually not inspecting the whole output, but only the Keys
, which are the same in the examples above, because the grouping is done by the same thing (box.BoxId
).
However, replace the last line:
select q.Key;
with
select q;
You will notice that:
group 1 by ...
query will return an IGrouping<int, int>
which will have all values set to 1group box by ...
query will return an IGrouping<int, Box>
, which will have all the boxId keys and, for each of them, the corresponding Box
objects with respect to the grouping criteria.Upvotes: 2