明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

泛型转DataTable方法

Posted on 2009-05-22 10:59  且行且思  阅读(1188)  评论(1编辑  收藏  举报

 

/// 将集合类转换成DataTable
    
/// </summary>
    
/// <param name="list">集合</param>
    
/// <returns></returns>
    public DataTable ToDataTable(List<GongGaoInfo> list)
    {
        DataTable result 
= new DataTable();
        
if (list.Count > 0)
        {
            PropertyInfo[] propertys 
= list[0].GetType().GetProperties();
            
foreach (PropertyInfo pi in propertys)
            {
                result.Columns.Add(pi.Name, pi.PropertyType);
            }
            
for (int i = 0; i < list.Count; i++)
            {
                ArrayList tempList 
= new ArrayList();
                
foreach (PropertyInfo pi in propertys)
                {
                    
object obj = pi.GetValue(list[i], null);
                    tempList.Add(obj);
                }
                
object[] array = tempList.ToArray();
                result.LoadDataRow(array, 
true);
            }
        }
        
return result;
    }