其他类型转化成DataTable
2017-11-08 14:17
218 查看
class Program { static void Main(string[] args) { List<Student> list = new List<Student>(); list.Add(new Student() { ID = 1, Name = "Fabre", Sex = true, Age = 27, Birthday = DateTime.Now }); string[] strTitle = new string[] { "ID", "Name", "Sex", "Age", "Birthday" }; DataTable dt = GetDataTable(list, strTitle); } public static DataTable GetDataTable(dynamic objects, string[] strFields) { DataTable dt = new DataTable(); bool isFirst = true; foreach (var obj in objects) { DataRow dr = dt.NewRow(); foreach (string item in strFields) { if (isFirst) { dt.Columns.Add(item);//创建列 } dr[item] = GetPropertyValue(obj, item);//单元格赋值 } isFirst = false;//第一次创建表头,往后都不用创建了,用一个标识处理 dt.Rows.Add(dr); } return dt; } /// <summary> /// 获取一个实例指定的属性值 /// </summary> /// <param name="info">object对象</param> /// <param name="field">属性名称</param> /// <returns></returns> public static object GetPropertyValue(object info, string field) { if (info == null) { return null; } Type t = info.GetType(); IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; if (property.Count() < 1) { return ""; } return property.First().GetValue(info, null); } } public class Student { public int ID { get; set; } public string Name { get; set; } //true 男 false 女 public bool Sex { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } }
相关文章推荐
- QT QString, wchar_t *, TCHAR, CString和其他字符或字符串类型的转化
- 把datetime类型的日期转化成年月日或其他格式方法总结
- 将List<T>转化成 DataTable--调整可空类型的转化错误
- Java string 类型与其他类型的转化(string.valueof())
- Java基础知识强化59:String(字符串)和其他类型的相互转化
- 句柄转化为字符串 与 其他数据类型转换为字符串
- CString和其他类型转化
- Java String与其他类型之间的转化及其算法练习
- JS其他类型值转化为Boolean类型规则
- 实体类与DataTable的转化(适用任意类型)
- QT QString, wchar_t *, TCHAR, CString和其他字符或字符串类型的转化
- CString 转化为其他类型
- PHP中其他类型转化为Bool类型的变化情况
- byte数组和其他数据类型之间的转化
- char* 转化为其他类型
- 【字符串到其他类型转化】stringstream用法
- 浅谈PHP中其他类型转化为Bool类型
- int 转化为其他类型
- VB中 byte数组和其他数据类型之间的转化
- C#把datetime类型的日期转化成年月日或其他格式方法总结