This is how to do a distinct in a datatable in Visual Basic. It is derived from http://support.microsoft.com/default.aspx?scid=kb;en-us;326176#1 and also look at this definition http://weblogs.asp.net/eporter/archive/2005/02/10/370548.aspx for multiple columns / fields.
Private
Function ColumnEqual(ByRef A As Object, ByRef B As Object) As Boolean ' Compares two values to see if they are equal. Also compares DBNULL.Value.' Note: If your DataTable contains object fields, then you must extend this
' function to handle them in a meaningful way if you intend to group on them. If IsDBNull(A) And IsDBNull(B) Then Return True End If If IsDBNull(A) Or IsDBNull(B) Then Return False End If If A = B Then Return True End If End Function Public Function SelectDistinct(ByVal TableName As String, ByRef SourceTable As DataTable, ByVal FieldName As String) As DataTable Dim dt As New DataTable(TableName) Dim dr As DataRow
dt.Columns.Add(FieldName, SourceTable.Columns(FieldName).DataType)
Dim LastValue As Object = DBNull.Value For Each dr In SourceTable.Select("", FieldName) If IsDBNull(LastValue) Or Not ColumnEqual(LastValue, dr(FieldName)) ThenLastValue = dr(FieldName)
dt.Rows.Add(LastValue)
End If Next Return dt End Function
No comments:
Post a Comment