VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,564 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
HI
I want to choose non-duplicate elements in DataTable
Where DataTable contains data as follows
TABLE A
COLUMN A
AM1
AM5
AM6
AM5
AM1
AM1
AM1
Where the final output is datatable= AM6
Blockquote
Public Function RemoveDuplicateRowsG(ByVal dTable As DataTable) As DataTable
For intI = dTable.Rows.Count - 1 To 0 Step -1
For intJ = intI - 1 To 0 Step -1
If dTable.Rows(intI)(0) = dTable.Rows(intJ)(0) Then
dTable.Rows.RemoveAt(intI)
dTable.Rows.RemoveAt(intJ)
Exit For
End If
Next
Next
dTable.AcceptChanges()
Return dTable
End Function
It seems that you are also interested in fixing your loops. Consider this approach too:
dTable.AcceptChanges()
For i = 0 To dTable.Rows.Count - 1
If dTable.Rows(i).RowState = DataRowState.Deleted Then Continue For
Dim v = dTable.Rows(i)(0).ToString
For j = i + 1 To dTable.Rows.Count - 1
If dTable.Rows(j).RowState = DataRowState.Deleted Then Continue For
If dTable.Rows(j)(0).ToString = v Then
dTable.Rows(j).Delete()
dTable.Rows(i).Delete()
End If
Next
Next
dTable.AcceptChanges()
Hi,
you can use LinQ expression like in following console demo:
Module Module73
Sub Main()
Try
Dim c As New Demo
c.Execute()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Console.WriteLine("Continue enter key")
Console.ReadKey()
End Sub
Friend Class Demo
Friend Sub Execute()
Try
Dim dTable As DataTable = GetDataTable()
Dim q = From row In dTable.AsEnumerable Group row By Key = row(0) Into Group Where Group.Count = 1 Select result = Key
For Each r In q
Console.WriteLine(r)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Private Function GetDataTable() As DataTable
Dim str() As String = New String() {"AM1", "AM5", "AM6", "AM5", "AM1", "AM1", "AM1"}
Dim dt As New DataTable("TableA")
dt.Columns.Add("ColumnA", GetType(String))
For Each item In str
dt.Rows.Add(item)
Next
Return dt
End Function
End Class
End Module
Result:
AM6
Continue enter key