Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Table to DataTable casting

Tags:

c#

linq

dataset

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.

like image 493
Zaromia Avatar asked Dec 29 '22 07:12

Zaromia


1 Answers

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/

like image 75
BFree Avatar answered Jan 01 '23 17:01

BFree