Wednesday, January 30, 2008

Distinct DataTable

. Wednesday, January 30, 2008

Distinct è la clausola che ci permette di eliminare ripetizioni dai risultati di una select.
Nativamente nel Framework 1.x non esiste un metodo che ci permetta di fare una Distinct su un oggetto DataTable, ma abbiamo tutti gli strumenti
per costruire un metodo ad hoc.
La soluzione che ho adottato sfrutta l'uso di un hashtable per conservare i valori univoci:

   1: 'VB.NET
   2: Private Function DistinctDt(ByVal dt As DataTable, ByVal colDistinct As Integer) As DataTable
   3:   Dim dtDistinct As DataTable = New DataTable()
   4:   Dim htKey As Hashtable = New Hashtable()
   5:   For Each row As DataRow In dt.Rows
   6:     If Not (htKey.Contains(row(colDistinct))) Then
   7:       dtDistinct.ImportRow(row)
   8:       htKey.Add(row(colDistinct), Nothing)
   9:     End If
  10:   Next
  11: Return dtDistinct
  12: End Function


   1: //C#
   2: private DataTable DistinctDt( DataTable dt, int colDistinct)
   3: {
   4:   DataTable dtDistinct = new DataTable();
   5:   Hashtable htKey = new Hashtable();
   6:   foreach( DataRow row in dt.Rows)
   7:   {
   8:     if( !htKey.Contains( row[ colDistinct]))
   9:     {
  10:       dtDistinct.ImportRow( row);
  11:       htKey.Add(row[colDistinct], null);
  12:     }
  13:   }
  14:   return dtDistinct;
  15: }

Il metodo accetta come parametri un oggetto DataTable su cui eseguire la Distinct ed inoltre un intero, cioè l'indice della colonna
su cui applicare la clausola (volendo si può anche passare il nome della DataColumn).
Il corpo del metodo è molto semplice, da sottolineare soltanto l'uso del metodo ImportRow che copia una DataRow in una DataTable,
conservando però tutte le impostazioni delle proprietà dell'oggetto copiato.

0 commenti:

Post a Comment