Because I had to write a DistinctRows function last night, today I looked at the May bits of VS2005 to see if they had addressed this really obvious need, and indeed they did! Hooray hoorah!
OverLoads Public Function ToTable( _ ByVal distinct As , _ ByVal columnNames() As _) As
Here’s the quick hack I wrote last night if you want to use it. It sorts the table on the keyfield then walks through it grabbing every row where the value of the key field changes and stuffing it into a new datatable that is returned. No rocket science. Just another one of those things I wonder why I had to write the code.
(note – the int32_key is in there as a reminder in case I need to create another one for non-int keys)
Public Function DistinctRows_Int32_Key(ByVal dt As DataTable, ByVal keyfield As String) As DataTable
Dim newTable As DataTable = dt.Clone
Dim keyval As Int32 = 0
Dim dv As DataView = dt.DefaultView
dv.Sort = keyfield
If dt.Rows.Count > 0 Then
For Each dr As DataRow In dt.Rows
If Not dr.Item(keyfield) = keyval Then
keyval = dr.Item(keyfield)
newTable = dt.Clone
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!
3 thoughts on “ADO.NET 2.0: DataView.ToTable DISTINCT!! Hooray Hooray!”
you can find a detailed help of DataView here vb.net-informations.com/…/ado.net-datavie
Your function above does have a small mistake. In order to retain the sort order you set, you need to alter your For Each line to use the Dataview and not the original Datatable.
For Each dr As DataRow In dv.ToTable.Rows
Thanks for help in framing this out.
hi you can directly get distinct from dataview refer here
<a href=’http://www.vbknowledgebase.com/WebApp/Guest/Home/Home.aspx?PageCode=70&Desc=Asp-.Net-DataTable-DataSet-Distinct-using-ToTable’>DataSet Distinct using ToTable</a>