How to cast
System.Data.Linq.Table<T> to System.Data.DataTable
        DemoDBDataContext context = new DemoDBDataContext();
        DataSet ds = new DataSet();
        var query = context.Customers;   
        ds.Tables[0] = query;
How to do that? the assignment
ds.Tables[0] = query;
It throws
Property or indexer
System.Data.DataTableCollection.this[int]cannot be assigned to it is read only.
You can't cast a System.Data.Linq.Table to a DataTable, however you can easily write an extension method on IEnumerable to convert it to a DataTable:
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
    var tb = new DataTable(typeof(T).Name);
        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }
    foreach (var item in items)
    {
        var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
           values[i] = props[i].GetValue(item, null);
        }
        tb.Rows.Add(values);
    }
    return tb;
}
Source: http://www.chinhdo.com/20090402/convert-list-to-datatable/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With