Usualmente cuando trabajamos con un objeto DataTable, nos vemos en la necesidad de filtrar los datos del mismo. Para esto podemos usar un DataView, asociado al DataTable, o utilizar el metodo Select() del DataTable para retornar un set de datos, aplicandoles un criterio.
 
El unico inconveniente que posee el metodo Select(), es que retorna un Array de DataRow. La forma usual de trabajar con este metodo seria
 

Sub Sample1()

  Dim dt As DataTable

  Dim sort As String

  Dim filter As String

  Dim rows As DataRow()

  ‘ get data

  dt = getdata()

  ‘ sort and filter data

  rows = dt.Select(filter, sort)

  ‘ work with selected rows

  For Each dr As DataRow In rows

    ‘ some work

  Next

End Sub

 
Sin embargo, ya que Ado.Net nos brinda un modelo de objetos mas que poderoso, parece poco apropiado trabajar con un Array.
Una solucion que cree para este problema, fue la siguiente funcion
 

Function SelectDataTable(ByVal dt As DataTable, ByVal filter As String, ByVal sort As String) As DataTable

  Dim rows As DataRow()

  Dim dtNew As DataTable

  ‘ copy table structure

  dtNew = dt.Clone()

  ‘ sort and filter data

  rows = dt.Select(filter, sort)

  ‘ fill dtNew with selected rows

  For Each dr As DataRow In rows

    dtNew.ImportRow(dr)

  Next

  ‘ return filtered dt

  Return dtNew

End Function

 
La misma  aplica un filtro en una DataTable y con el Array de DataRows que retorna, crea una nueva tabla y la retorna. El codigo del primer ejemplo, quedaria de la siguiente manera
 

Sub Sample2()

  Dim dt As DataTable

  Dim dtNew As DataTable

  ‘ get data

  dt = getdata()

  ‘ sort and filter data

  dtNew = SelectDataTable(dt, "Filter", "sort")

  ‘ work with selected rows

  For Each dr As DataRow In dtNew.Rows

    ‘ some work

  Next

End Sub

 
Otra opcion es heredar de DataTable y agregar este metodo
 
En la nueva version de Ado.Net, este problema estara solucionado, sino podemos votarlo en http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5421ba0b-0474-41c4-ac6f-8ce226b28ae8.
 
Saludos
 
PD: Tb lo publique en el Guille  http://tinyurl.com/8wgry
 

Leave a comment

Discover more from El Bruno

Subscribe now to keep reading and get access to the full archive.

Continue reading