2

我在 VB 页面中有一个包含批量数据的数据表。在该数据表中,有一列名为 vType,该列中的值是 Pr 定义的值之一,例如“A”、“B”、“C”、“D”等,它来自一个Datable。现在我想在最后计算每种类型。例如:CountA = 20,CountB=25 等等。

到目前为止,我已经使用静态的 If 条件比较了每个值

For each dr as dataRow in dsType.rows
If dr("vType") = 'A' Then
                    CountA += 1
ElseIf dr("vType") = 'B' Then
                    CountB +=1
Next dr

并且此 If 条件将重复取决于该数据表中没有类型(最多 8 个固定值)我想在单个 if 条件中执行此操作(如果可能,则为动态)我可以计算这些值并将其存储到单个变量中吗?感谢您的及时回复。

4

3 回答 3

1

您可以在每个组上使用Linq-To-DataSetEnumerable.GroupBy+ :Enumerable.Count

Dim typeGroups = dsType.AsEnumerable().
    GroupBy(Function(row) row.Field(Of String)("vType")).
    Select(Function(g) New With{ .Type = g.Key, .Count = g.Count(), .TypeGroup = g })

请注意,New With在 VB.NET 中创建一个具有自定义属性的匿名类型。因此,就像您可以在当前方法中使用的即时类一样。

现在您可以使用以下命令枚举查询For Each

For Each typeGroup In typeGroups
    Console.WriteLine("Type:{0} Count:{1}", typeGroup.Type, typeGroup.Count)
Next

我不能使用 Linq,我只需要使用简单的 vb

然后使用Dictionary

Dim typeCounts = New Dictionary(Of String, Integer)
For Each row As DataRow In dsType.Rows
    Dim type = row.Field(Of String)("vType")
    If (typeCounts.ContainsKey(type)) Then
        typeCounts(type) += 1
    Else
        typeCounts.Add(type, 1)
    End If
Next

现在您有一个字典,其中键是类型,值是具有此类型的行数。

于 2013-06-26T12:03:54.660 回答
0

为什么不从数据库本身获得假装结果?像这样:

select count(*), vType
from someTable
group by vType
于 2013-06-26T12:03:33.667 回答
0

不太确定你的问题..但这是我考虑过的..

您可以将其设置为 Sub ..

Sub AssignIncr(ByVal ds as DataSet,byval sFi as String,byval sCrit as String,ByRef Counter as Integer)
  For each dr as dataRow in ds.rows
    If dr(sFi) = sCrit Then Counter += 1
  Next dr
End Sub

所以你可以通过..

AssignIncr(dsType,"vType","A",CountA)
于 2013-06-26T12:31:59.920 回答