c# 将实体类集合转化为datetable格式案例

来源:互联网 发布:剑灵捏脸数据人男 编辑:程序博客网 时间:2024/06/06 04:58
class Program
    {
        static void Main(string[] args)
        {
            var list = new List<Demo> {  
                   new Demo{ id=1,age=18, name="Tim"},  
                    new Demo{ id=2,age=22, name="Allen"},  
                   new Demo{ id=3,age=24, name="Jim"}  
               };
            var dt = list.ToDataTable();
           
        }
    }
    static class Extensions
    {
        internal static DataTable ToDataTable<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
 
            var t = new DataTable();
 
            elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (T item in list)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return t;
        }
    }
    class Demo
    {
        public int id { getset; }
        public string name { getset; }
        public int age { getset; }
    }

第二种

var list = new List<Demo> {  
                   new Demo{ id=1,age=18, name="Tim"},  
                    new Demo{ id=2,age=22, name="Allen"},  
                   new Demo{ id=3,age=24, name="Jim"}  
               };

 DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("age", typeof(int));
            dt.Columns.Add("name", typeof(string));
            object[] values = new object[3];
            for (int i = 0; i < list.Count; i++)
            {
                AvgFWS item = data[i];
                values[0] = item.id;
                values[1] = item.age;
                values[2] = item.name;
                dt.Rows.Add(values);
            }
            return dt;

案例来自于:http://bbs.csdn.net/topics/390385021?page=1
原创粉丝点击