List转DataSet

class Demo
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }
    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 ds = list.ToDataSet();
            string s=ds.Tables[0].Rows[1][1].ToString();
        }
    }

    static class Extensions
    {
        internal static DataSet ToDataSet<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            var ds = new DataSet();
            var t = new DataTable();
            ds.Tables.Add(t);
            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 ds;
        }
    }

转载自:csdn tim
原文地址:https://www.cnblogs.com/i80386/p/2253133.html