navigation
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:

Convert Linq Query results to Datatable in asp.net Csharp