VB.NET LINQ Group by Multiple Columns

时间:2012-09-18 17:50:40

标签: vb.net linq group-by

我有以下LINQ代码,它有语法错误,我不知道如何解决它

         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

所以我做错了什么?

以下是该表的外观,我想按列cprice和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 |      |
+---------------+---------------+-----------+------+

1 个答案:

答案 0 :(得分:4)

试试这个:

new with { Key.Price = row.Field(Of Double)("cprice") ,
           Key.Category = row.Field(Of Integer)("ccategory")

使用Key修饰符,这会创建一个基于equality of its members实现相等的匿名类型。