List转换成DataSet

List转换成DataSet,强大的泛型

public  static DataSet ConvertToDataSet(this IList list)

      {
          //获取泛型类型
          Type elementType = typeof(T);
          var ds = new DataSet();
          var t = new DataTable();
          ds.Tables.Add(t);
          elementType.GetProperties().ToList().ForEach(elementInfo => t.Columns.Add(elementInfo.Name, Nullable.GetUnderlyingType(elementInfo.PropertyType)));
          foreach(T item in list)
          {
              var row = t.NewRow();
              elementType.GetProperties().ToList().ForEach(elementInfor => row[elementInfor.Name] = elementInfor.GetValue(item, null) ?? DBNull.Value);
              t.Rows.Add(row);
          }
          return ds;

      }

示例:

var list = new List {  
  new personInfor{ id=1,age=18, name="jack"},  
  new personInfor{ id=2,age=25, name="Allenc"},  
 new personInfor{ id=3,age=20, name="Jam"}  
};  
var ds = list.ConvertToDataSet();  
GridView1.DataSource = ds.Tables[0];  
GridView1.DataBind();


你可能感兴趣的:(C#的Forever)