C#对象、List<>转DataTable

2021-01-20 04:12

阅读:539

标签:bsp   datarow   eric   next   table   ati   type   object   ict   

 public static DataTable ObjectToTable(object obj)
        {
            try {
                Type t;
                if (obj.GetType().IsGenericType)
                {
                    t = obj.GetType().GetGenericTypeDefinition();
                }
                else
                {
                    t = obj.GetType();
                }
                if(t== typeof(List)||
                    t==typeof(IEnumerable))
                {
                    DataTable dt = new DataTable();
                    IEnumerable  lstenum=obj as IEnumerable;
                    if(lstenum.Count()>0)
                    {
                        var ob1 = lstenum.GetEnumerator();
                        ob1.MoveNext();
                        foreach (var item in ob1.Current.GetType().GetProperties())
                        {
                            dt.Columns.Add(new DataColumn() { ColumnName = item.Name });
                        }
                        //数据
                        foreach (var item in lstenum)
                        {
                            DataRow row = dt.NewRow();
                            foreach (var sub in item.GetType().GetProperties())
                            {
                                row[sub.Name] = sub.GetValue(item, null);
                            }
                            dt.Rows.Add(row);
                        }
                        return dt;
                    }
                }
                else if (t == typeof(DataTable))
                {
                    return (DataTable)obj;
                }
                else   //(t==typeof(Object))
                {
                    DataTable dt = new DataTable();
                    foreach (var item in obj.GetType().GetProperties())
                    {
                        dt.Columns.Add(new DataColumn() { ColumnName=item.Name });                       
                    }
                    DataRow row= dt.NewRow();
                    foreach (var item in obj.GetType().GetProperties())
                    {
                        row[item.Name] = item.GetValue(obj, null);
                    }                    
                    dt.Rows.Add(row);
                    return dt;
                }
                 
            }catch(Exception ex)
            {               
            }
            return null;
        }

C#对象、List转DataTable

标签:bsp   datarow   eric   next   table   ati   type   object   ict   

原文地址:https://www.cnblogs.com/pzxnet/p/12148753.html


评论


亲,登录后才可以留言!