How to convert DataSet to List

In this post, I am going to show you a very useful c# code snippet that converts DataSet to List.

   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;
        }

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru