In my previous blog post about mapping data rows to objects you saw how easy it was to use reflection to map a data row to an object. With a little extra effort you can map data tables to a list of those mapped objects. The code below builds on my previous blog and will not work unless you have the code from that blog entry.
Public Shared Function MapDataTableToList(Of T)(ByVal dt As DataTable) As IList(Of T)
If dt Is Nothing Then
Return Nothing
End If
Dim list As IList(Of T) = New List(Of T)
For Each dr As DataRow In dt.Rows
list.Add(MapDatarowToObject(Of T)(dr))
Next
Return list
End Function
To explain how this works we’ll go line by line
Public Shared Function MapDataTableToList(Of T)(ByVal dt As DataTable) As IList(Of T)
I’m creating a method that needs to be called by defining a type for T. The only parameter is a data table. An example of calling this method looks like this:
Dim dt As DataTable = GetDataTableFromDb()
Dim usersList As IList(Of User) = MapDataTableToList(Of User)(dt)
This would convert a data table to a generic list (IList) of user objects.
If dt Is Nothing Then
Return Nothing
End If
These lines of code make sure that the data table parameter has a value.
Dim list As IList(Of T) = New List(Of T)
Create a generic list of objects based on T. T is the generic type specified when calling the method. In the example usage above the T parameter would be of type User.
For Each dr As DataRow In dt.Rows
list.Add(MapDatarowToObject(Of T)(dr))
Next
Iterate through each data row in the data table and call MapDatarowToObject (from the previous blog entry) and add the mapped object to the list.
Return list
Return the list of objects from the method.
So there you go, An easy to use data table to object mapper.
Until next time.
posted @ Wednesday, July 30, 2008 8:44 AM