Tuesday, April 8, 2014

C# Convert Linq to Data Table


  1. Use the Following Method to Convert your Linq object to Datatable.
public static DataTable LinqToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dt = null;

            if (varlist == null)
                return dt;
            else
                dt = new DataTable();

            PropertyInfo[] props = null;

            foreach (T row in varlist)
            {
                if (props == null)
                {
                    props = ((Type)row.GetType()).GetProperties();

                    foreach (PropertyInfo pi in props)
                    {
                        dt.Columns.Add(pi.Name, typeof(String));
                    }
                }

                DataRow dr = dt.NewRow();

                foreach (PropertyInfo pi in props)
                {
                    dr[pi.Name] = pi.GetValue(row, null) == null ? DBNull.Value : pi.GetValue(row, null);
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }

No comments:

Post a Comment