Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I have been playing around with grouping items using LINQ, and I am not sure if there is a difference between these two syntaxes:
VB
Dim categories1 =
    From p In products Group p By p.Category Into Group,
        TotalUnits = Sum(p.UnitsInStock), ProductCount = Count()
    Select Category, Average = TotalUnits / ProductCount

Dim categories2 =
    From p In products Group p By p.Category Into
        TotalUnits = Sum(p.UnitsInStock), ProductCount = Count()
    Select Category, Average = TotalUnits / ProductCount


In the first, I do "Into Group," and in the second I do "Into". It seems that the "Group" in that case is a keyword rather than the name of the group. Both syntaxes appear to produce the same result. Is there a reason these two syntaxes exist (e.g., can one be used when the other cannot)? Is the second syntax just shorthand for the first?

Here is a class and function you can use to test the above queries, if you like:
VB
Public Class ProductClass
	Public Property Category As String
	Public Property UnitsInStock As Integer
End Class
Public Function GetProductList() As List(Of ProductClass)
	Return New List(Of ProductClass) From {
		New ProductClass With {.Category = "A", .UnitsInStock = 5},
		New ProductClass With {.Category = "A", .UnitsInStock = 3},
		New ProductClass With {.Category = "B", .UnitsInStock = 4}}
End Function
Posted

1 solution

The keyword "Into Groups" will add a variable containing all of the matching items. "Into group" will be prefer in that case when you have to use multiple groups to collect fields.

You can see this link:
http://geekswithblogs.net/WillSmith/archive/2008/05/28/linq-joins-and-groupings.aspx[^]

In this link, the author has selected the fields from two groups, now you can understand the difference of "Into" and "Into Group"

If you need converter for C# to VB.Net:
Here is the Converter[^].
 
Share this answer
 
Comments
AspDotNetDev 26-Aug-11 17:27pm    
Like I said, "Group" in my case seems to be a keyword rather than a variable, as it seems the author of that blog post is doing in C#. If I use something aside from "Group" (e.g., "Into MyGroup"), intellisense will add parens and complain that the syntax is incorrect. I believe I know the VB.NET syntax ("Into MyGroup = Group") for the C# syntax in the blog post, and it is not the same as what I'm talking about in my question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900