c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
c# .net

Convert Linq Query results to Datatable in asp.net C#

| | CSharp , Linq

This extension method helps you to convert linq Query results (Generic List) to Datatable.

 The following code explains you how to call this extension method.

var result = (from order in db.Orders.AsEnumerable()
                          group order by order.ShipCity into rowGroup
                          select new
                          {
                              ShipCity =rowGroup.Key,
                            TotalOrders =rowGroup.Count()
                         }).Distinct().ToList();
            DataTable dt =ToDataTable(result);

 

public static DataTable ToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
               table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ??prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                   row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
               table.Rows.Add(row);
            }
            return table;
        }

Output: