扩展方法 DataTable的ToList<T>

 

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Reflection;
 
namespace Extension
{
 
    public static class Extension
    {
        public static IList<T> ToList<T>(this DataTable dt)
        {
            var lst = new List<T>();
            var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T t = System.Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        if (!Convert.IsDBNull(item[i]))
                        {
                            info.SetValue(t, item[i], null);
                        }
                    }
                }<br>                lst.Add(t);
            }
            return lst;
            ///throw new NotImplementedException();
        }
 
    }
}

DataTable dt =gettable();

var u = dt.ToList<user>();

posted on 2020-03-22 20:50  欢笑一声  阅读(173)  评论(0)    收藏  举报

导航