ITPub博客

首页 > 应用开发 > IT综合 > Convert Array of Objects to Data Table

Convert Array of Objects to Data Table

原创 IT综合 作者:yuzhangqi 时间:2010-12-20 16:54:19 0 删除 编辑

Normally in a web application, the Presentation Layer retrieves an Array/Collection of business objects as the data source to bind to GridView control. However sometimes we do need a DataTable to return. In such cases we need convert an Array/Collection of object to a DataTable.

Now let's look into te code.

[C#]

public DataTable ConvertArrayToTable(Array myList)
{
DataTable dt = new DataTable();
if (myList.Length > 0)
{
PropertyInfo[] propInfos = myList.GetValue(0).GetType().GetProperties();

foreach (PropertyInfo propInfo in propInfos)
{
dt.Columns.Add(propInfo.Name, propInfo.PropertyType);
}

foreach (object tempObject in myList)
{
DataRow dr = dt.NewRow();

for (int i = 0; i < propInfos.Length; i++)
{
dr[i] = propInfos[i].GetValue(tempObject, null);
}

dt.Rows.Add(dr);
}
}

return dt;
}

[VB.NET]

Public Shared Function ConvertArrayToDataTable(ByVal list As ArrayList) As DataTable
Dim table As New DataTable()

If list.Count > 0 Then
Dim iterator As IEnumerator = list.GetEnumerator()
iterator.MoveNext()
Dim propInfos As PropertyInfo() = iterator.Current.GetType().GetProperties()

For Each propInfo As PropertyInfo In propInfos
table.Columns.Add(propInfo.Name, propInfo.PropertyType)
Next

For Each obj As Object In list
Dim row As DataRow = table.NewRow()

For i As Int32 = 0 To propInfos.Count - 1
row.Item(i) = propInfos(i).GetValue(obj, Nothing)
Next

table.Rows.Add(row)
Next

End If

Return table
End Function

References

http://www.codekeep.net/snippets/76bd0207-ea91-4086-81fc-c47a83339512.aspx

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/13651903/viewspace-1043351/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-06-10

  • 博文量
    102
  • 访问量
    763298