I want to convert the linq query results to datatable so that I can assign datatable to GridView to show it on asp page.
However I am not able to convert the results
If you want to have you own extension method then you could always do something like this:
public static DataTable ToDataTable(this IQueryable items)
{
Type type = typeof(T);
var props = TypeDescriptor.GetProperties(type)
.Cast()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
.Where(propertyInfo => propertyInfo.IsReadOnly == false)
.ToArray();
var table = new DataTable();
foreach (var propertyInfo in props)
{
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}
foreach (var item in items)
{
table.Rows.Add(props.Select(property => property.GetValue(item)).ToArray());
}
return table;
}
You will need to reference both of these
using System.ComponentModel;
using System.Data;