IList转DataSet(支持Nullable)

来源:互联网 发布:java jsonarray 添加 编辑:程序博客网 时间:2024/04/30 19:08
public static DataSet ConvertToDataSet<T>(IList<T> list)
        
{
            
if (list == null || list.Count <= 0)
                
return null;

            DataSet ds 
= new DataSet();
            DataTable dt 
= new DataTable(typeof(T).Name);
            DataColumn column;
            DataRow row;

            System.Reflection.PropertyInfo[] myPropertyInfo 
=
                
typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            
foreach (T t in list)
            
{
                
if (t == nullcontinue;
                row 
= dt.NewRow();

                
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                
{
                    System.Reflection.PropertyInfo pi 
= myPropertyInfo[i];
                    String name 
= pi.Name;
                    
                    
if (dt.Columns[name] == null)
                    
{
                        
if (pi.PropertyType.UnderlyingSystemType.ToString() == "System.Nullable`1[System.Int32]")
                        
{
                            column 
= new DataColumn(name,typeof(Int32));
                            dt.Columns.Add(column);
                            
//row[name] = pi.GetValue(t, new object[] {i});//PropertyInfo.GetValue(object,object[])
                            if (pi.GetValue(t, null!= null)
                                row[name] 
= pi.GetValue(t, null);
                            
else
                                row[name] 
= System.DBNull.Value;
                        }

                        
else
                        
{
                            column 
= new DataColumn(name, pi.PropertyType);
                            dt.Columns.Add(column);
                            row[name] 
= pi.GetValue(t, null);
                        }

                    }

                }

                dt.Rows.Add(row);
            }

            ds.Tables.Add(dt);
            
return ds;
        }
 
原创粉丝点击