1

我正在尝试从数据表中的特定列中检索所有不同的值。数据表中的列名是“Count”。我有 2240 行,并且在“计数”列中有 6 个不同的值。问题是,当我执行以下代码时,它给了我行数而不是 6 个不同的值。

Dim counts = (From row In loadedData
Select row.Item("Count")).Distinct()
For Each i In counts
    MsgBox(i)
Next

如何修改它以检索 6 个不同的值,而不是给我总行数?

4

3 回答 3

9

您只需选择列并使用Enumerable.Distinct

Dim distinctCounts As IEnumerable(Of Int32) = loadedData.AsEnumerable().
    Select(Function(row) row.Field(Of Int32)("Count")).
    Distinct()

在查询语法中(我不知道甚至Distinct在 VB.NET 中直接支持):

distinctCounts = From row In loadedData
                 Select row.Field(Of Int32)("Count")
                 Distinct
于 2013-10-08T12:42:41.310 回答
6

您可以为此使用 ToTable(distinct As Boolean, ParamArray columnNames As String()) 方法。

loadedData.DefaultView.ToTable(True, "Count")

这将为您返回不同的用户。如果需要,您可以添加多个列名。

这是 msdn 文档。 https://msdn.microsoft.com/en-us/library/wec2b2e6(v=vs.110).aspx

于 2015-09-29T11:39:58.660 回答
0

如果需要,您也可以应用此逻辑,首先通过 columName 对数据表进行排序,然后应用此逻辑

    dtRecords.DefaultView.Sort = "columnName"
    dtRecords = dtRecords.DefaultView.ToTable
    Dim totalRecords As Integer = 0
    Dim thNameStr As String = filter(dtRecords, "columnName", totalRecords )

Public Shared Function filter(ByVal dtRecords As DataTable, ByVal columnName As String, ByRef totalRecords As Integer) As String
            Dim FilterStr As String = ""
            Dim eachTotal As Integer = 0
            totalRecords = 0
            Dim lastName As String = ""
            For rCount = 0 To dtRecords.Rows.Count - 1
                If lastName <> "" And lastName <> dtRecords.Rows(rCount)("" & columnName) Then
                    FilterStr &= lastName & " - [" & eachTotal & "]"
                    eachTotal = 0
                    totalRecords += 1
                End If
                lastName = dtRecords.Rows(rCount)("" & columnName)
                eachTotal += 1
            Next
            FilterStr &= lastName & " - [" & eachTotal & "]"
            totalRecords += 1
            Return FilterStr 
        End Function
于 2014-10-17T05:07:07.393 回答