VB.NET过滤/分组数据表

时间:2012-07-17 10:57:45

标签: linq datatable vb.net-2010

示例场景

我在数据库中有一个表,其中包含以下字段: - SerialNo,GroupNo,Description,Quantity。目前我正在使用ADO.NET DataSet填充的DataTable循环,我将字段添加到List中,如下所示......

' Gets the items from the database and created a DataSet
' The DataSet has a named DataTable called MyTable
ds = GetItems 

' Item is an model in my MVC project
Dim Item As Item

' I am creating a List of items...
i As List(Of Item)

For Each row As DataRow In ds.Tables("MyTable").Rows
    Item = New Item() With {
        .SerialNo = If(Not IsDBNull(row("SerialNo")), CInt(row("SerialNo")), 0),
        .GroupNo = If(Not IsDBNull(row("GroupNo")), CStr(row("GroupNo")), ""),
        .Description = If(Not IsDBNull(row("Description")), CStr(row("Description")), ""),
        .Quantity = If(Not IsDBNull(row("Quantity")), CInt(row("Quantity")), 0)
    }

    ai.Add(Item)
Next

要求

而不是获取每一行我想要获得每个GroupNo的第一个出现并将此结果返回到List中。例如......

  • SerialNo = 1 GroupNo = 1说明=项目A数量= 100
  • SerialNo = 2 GroupNo = 1说明=项目B数量= 100
  • SerialNo = 3 GroupNo = 1说明=项目C数量= 100
  • SerialNo = 4 GroupNo = 2说明=项目D数量= 100
  • SerialNo = 5 GroupNo = 2说明=项目E数量= 100
  • SerialNo = 6 GroupNo = 3说明=项目F数量= 100
实际上应该修改

...以返回......

  • SerialNo = 1 GroupNo = 1说明=项目A数量= 100
  • SerialNo = 4 GroupNo = 2说明=项目D数量= 100
  • SerialNo = 6 GroupNo = 3说明=项目F数量= 100

我在.NET 4.0中使用Visual Studio 2010(VB.NET)。

我试图研究各种方法,但我要么试图提取所有4列似乎没有正确分组。注意:我不想将查询修改为仅返回数据子集。我需要使用代码对其进行过滤/分组。

1 个答案:

答案 0 :(得分:1)

因此,您只想将每个小组的第一个DataRow初始化为Item

Dim items = From row In ds.Tables("MyTable").AsEnumerable()
            Let GroupNo = row.Field(Of Int32)("GroupNo")
            Group row By GroupNo Into Group
            Select New Item() With {
                .GroupNo = GroupNo,
                .SerialNo = Group.First().Field(Of Int32)("SerialNo"),
                .Quantity = Group.First().Field(Of Int32)("Quantity"),
                .Description = Group.First().Field(Of String)("Description")
            }

如果您想将其复制到List(Of Item),则只需拨打items.ToList()