The method below converts an array of objects to a DataTable object in C#.
2016-06-10 17:15
621 查看
http://www.c-sharpcorner.com/blogs/dynamic-objects-conveting-into-data-table-in-c-sharp1
public static DataTable GetDataTableFromObjects(object[] objects) { if (objects != null && objects.Length > 0) { Type t = objects[0].GetType(); DataTable dt = new DataTable(t.Name); foreach (PropertyInfo pi in t.GetProperties()) { dt.Columns.Add(new DataColumn(pi.Name)); } foreach (var o in objects) { DataRow dr = dt.NewRow(); foreach (DataColumn dc in dt.Columns) { dr[dc.ColumnName] = o.GetType().GetProperty(dc.ColumnName).GetValue(o, null); } dt.Rows.Add(dr); } return dt; } return null; }
/// <summary> /// ToDataTable /// </summary> /// <typeparam name="T">实体</typeparam> /// <param name="items">实体集</param> /// <returns></returns> public static DataTable ToDataTable<T>(this IEnumerable<T> items) { var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in props) { tb.Columns.Add(prop.Name, prop.PropertyType); } foreach (var item in items) { var values = new object[props.Length]; for (var i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } tb.Rows.Add(values); } return tb; }
相关文章推荐
- Class and Object
- java Object
- Object.create() --- javascript一种新的对象创建方式
- object references an unsaved transient instance - save the transient instance before flushing: org.t
- Objective-C 【init/initWithFrame调用机制】
- Objective-C中的instancetype和id区别
- Objective-C 【KVO(键值监听)】
- Objective-C 【KVC(键值编码)】
- Objective-C --- - UIScrollView(梳理总结)
- Java FX 8 - Tableview: Display Objects Within Objects
- ObjectAnimatior 属性动画的相关属性
- POJ-3241-Object Clustering
- iOS开发之Objective-C与JavaScript的交互 ——stringByEvaluatingJavaScriptFromString
- toString(),String.ValueOf,(String)Object的区别
- Objective C类方法load和initialize的区别
- Gradle sync failed: Cannot locate factory for objects of type DefaultGradleConnector, as ConnectorSe
- CObject::Dump(CDumpContext& dc )函数的学习
- objective-c --单知识点运用---FMDatabase -- -数据库操作
- python3 报错: AttributeError: 'module' object has no attribute 'urlopen'
- 为什么在 Objective-C 中给 nil 发送消息程序不会崩溃?