Convert Array of Objects to Data Table

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博客 ” ,链接:http://blog.itpub.net/13651903/viewspace-1043351/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/13651903/viewspace-1043351/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值