其他类型转化成DataTable

来源:互联网 发布:js点击按钮退出全屏 编辑:程序博客网 时间:2024/05/22 06:32
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; }}