VB.NET LINQ Group By Multiple Columns
14,485
Try this:
new with { Key.Price = row.Field(Of Double)("cprice") ,
Key.Category = row.Field(Of Integer)("ccategory")
Uisng the Key
modifier, this creates an anonymous type that implements equality based on equality of its members.
Author by
user1570048
Updated on June 14, 2022Comments
-
user1570048 almost 2 years
I have the following LINQ code which has a syntax error and i've no idea how to fix it
Dim query = From row In mainDatatable.AsEnumerable 'the syntax Error is in the following line Group row By new { row.Field(Of Double)("cprice") , row.Field(Of Integer)("ccategory")} Into ProductGroups '************************** Dim grpNumber = 1 For Each grp In query For Each row In grp.ProductGroups row.SetField("gnum", grpNumber) Next grpNumber += 1 Next End Sub
so what am i doing wrong?
Here is how the table looks like and i want to group by the columns cprice and ccategory
+---------------+---------------+-----------+------+ | Product Name | cprice | ccategory | gnum | +---------------+---------------+-----------+------+ | Skirt Red | 99 | 1 | | | Jeans Blue | 49 | 2 | | | Jeans Black | 49 | 2 | | | Skirt Blue | 99 | 1 | | | T-shirt White | 20 | 2 | | | T-shirt Green | 20 | 2 | | | Jeans Grey | 49 | 2 | | +---------------+---------------+-----------+------+
-
user1570048 over 11 yearsthanks,the first option worked, but i didn't get the results i expected, i expect the products that have the same cprice and same ccategory to be in a group , so i have 5800 rows it gave me 5800 groups!
-
Gert Arnold over 11 yearsBit unexpected. Edited my answer.
-
Gert Arnold almost 11 yearsFor the record: in the mean time I've learned a bit more about equality of anonymous types in VB. See here.
-
toddmo over 9 yearsI could not get this to compile until I added
= Group
at the end of the statement -
Enigmativity almost 8 yearsTo use anonymous types in VB.NET you must use the
Key
modifier on the individual properties if you want to use them in a group-by\. -
Gert Arnold almost 8 years@Enigmativity Thanks for spotting this.