Implementing SELECT DISTINCT with DataTable.Select method

A

Andrea Caldarone

Hi all,

I've a standard DataTable, is there a way to get an array of value like that
one I obtain in SQL Server suppying the SELECT DISTINCT [field] statement?
Have I to loop trough the datatable to build the array or is there a simpler
way?
 
M

Miha Markic [MVP C#]

Hi Andrea,

No disctinct functionality there.
Loop is your best friend.
Also there is a 3rd party tool advertised in this newsgroup that does some
sql functionality over datasets (I keep forgotting its name - i have to
write it down).
 
A

Andrea Caldarone

Miha said:
Hi Andrea,

No disctinct functionality there.
Loop is your best friend.
Also there is a 3rd party tool advertised in this newsgroup that does
some sql functionality over datasets (I keep forgotting its name - i
have to write it down).

I've implemented a simple function that make the SELECT DISTINCT for me,
have a look:

Public Function SelectDistinct(ByRef tX As DataTable, ByVal strField As
String) As IList

Dim rQuery() As DataRow
Dim lRET As New Collection
Dim i As Integer
Dim j As Integer

'Sort the DataTable by the Field
rQuery = tX.Select("", strField & " ASC")

Select Case rQuery.GetUpperBound(0)
Case Is = -1

'no rows
Exit Select
Case Is = 0

'1 row
lRET.Add(CType(rQuery.GetValue(0), DataRow).Item(strField))
Case Else

'more than 1 row
lRET.Add(CType(rQuery.GetValue(0), DataRow).Item(strField))
j = 1

For i = 1 To rQuery.GetUpperBound(0)
If rQuery(i).Item(strField) <> lRET.Item(j) Then
lRET.Add(CType(rQuery.GetValue(i),
DataRow).Item(strField))
j += 1
End If
Next
End Select

'function return
Return lRET
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top