使用linq vb.net从数据表中检索不同的值

时间:2013-10-08 12:18:51

标签: vb.net linq datatable

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

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

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

3 个答案:

答案 0 :(得分:4)

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

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

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

distinctCounts = From row In loadedData
                 Select row.Field(Of Int32)("Count")
                 Distinct

答案 1 :(得分:2)

您可以使用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

答案 2 :(得分: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