问题
I am trying to retrieve all of the distinct values from a particular column in a datatable. The column name in the datatable is "Count". I have 2240 rows and I have 6 distinct values in the "Count" column. The problem is, when I execute the following code, it is giving me the number of rows rather than the 6 distinct values.
Dim counts = (From row In loadedData
Select row.Item("Count")).Distinct()
For Each i In counts
MsgBox(i)
Next
How can I modify this to retrieve the 6 distinct values, rather than it giving me the total number of rows?
回答1:
You just have to select the column and use Enumerable.Distinct:
Dim distinctCounts As IEnumerable(Of Int32) = loadedData.AsEnumerable().
Select(Function(row) row.Field(Of Int32)("Count")).
Distinct()
In query syntax(i didn't know that even Distinct is supported directly in VB.NET):
distinctCounts = From row In loadedData
Select row.Field(Of Int32)("Count")
Distinct
回答2:
You can use ToTable(distinct As Boolean, ParamArray columnNames As String()) method for this.
loadedData.DefaultView.ToTable(True, "Count")
This will return distinct Users for you. You can add multiple column names if you want.
Here is the msdn documentation. https://msdn.microsoft.com/en-us/library/wec2b2e6(v=vs.110).aspx
回答3:
you can also apply this logic if you want , first sort datatable through columName , then apply this logic
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
来源:https://stackoverflow.com/questions/19247504/retrieve-distinct-values-from-datatable-using-linq-vb-net