Linq Table to DataTable casting

How to do

System.Data.Linq.Table<T> before System.Data.DataTable

        DemoDBDataContext context = new DemoDBDataContext();
        DataSet ds = new DataSet();
        var query = context.Customers;   
        ds.Tables[0] = query;

How to do it? the appointment

ds.Tables[0] = query;

He throws

A property or indexer System.Data.DataTableCollection.this[int]cannot be assigned to it read-only.

+3
source share
1 answer

You cannot use System.Data.Linq.Table for a DataTable, however you can easily write an extension method in 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/

+7
source

Source: https://habr.com/ru/post/1726158/


All Articles