Skip to main content

How to convert DataSet to List

In this post I am going to show you a very useful c# code snippet that convert DataSet to List<T>.

 

   public static List<T> ToCollection<T>(this DataTable dt)
        {
            List<T> lst = new List<T>();
            Type tClass = typeof(T);
            PropertyInfo[] pClass = tClass.GetProperties();
            List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
            T cn;
            foreach (DataRow item in dt.Rows)
            {
                cn = (T)Activator.CreateInstance(tClass);
                foreach (PropertyInfo pc in pClass)
                {
                  
                   DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                   if (d != null)
                   {
                       if (item[pc.Name] != DBNull.Value)
                       {
                           pc.SetValue(cn, (item[pc.Name]), null);
                       }
                   }   
                }
                lst.Add(cn);
            }
            return lst;
        }

Comments

Popular posts from this blog