tags:

views:

390

answers:

1

How to cast

System.Data.Linq.Table 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.

+3  A: 

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/

BFree
Sorry for the delayed response.It is working and thanks for the link.
Zaromia