Friday 13 February 2015

convert from list to datatable in C#

    //public DataTable ConvertListToDataTable<T>(IList<T> data)// T is any generic type
        //{
        //    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

        //    DataTable table = new DataTable();
        //    for (int i = 0; i < props.Count; i++)
        //    {
        //        PropertyDescriptor prop = props[i];
        //        table.Columns.Add(prop.Name, prop.PropertyType);
        //    }
        //    object[] values = new object[props.Count];
        //    foreach (T item in data)
        //    {
        //        for (int i = 0; i < values.Length; i++)
        //        {
        //            values[i] = props[i].GetValue(item);
        //        }
        //        table.Rows.Add(values);
        //    }
        //    return table;
        //}

        //static DataTable ConvertListToDataTable(List<double> list)
        //{
        //    // New table.
        //    DataTable table = new DataTable();

        //    // Get max columns.
        //    int columns = 0;
        //    foreach (var array in list)
        //    {
        //        if (list.Count > 0)
        //        {
        //            columns = list[;
        //        }
        //    }

        //    // Add columns.
        //    for (int i = 0; i < columns; i++)
        //    {
        //        table.Columns.Add();
        //    }

        //    // Add rows.
        //    foreach (var array in list)
        //    {
        //        table.Rows.Add(array);
        //    }

        //    return table;
        //}

        //public DataTable ConvertListToDataTable<T>(List<T> lstData)
        //{
        //    DataTable dtLstToData = new DataTable(typeof(T).Name);
        //    //Get all the properties for dataColumn Name
        //    PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        //    foreach (PropertyInfo prop in Props)
        //    {

        //        dtLstToData.Columns.Add(prop.Name);
        //    }
        //    foreach (T data in lstData)
        //    {
        //        var values = new object[Props.Length];
        //        for (int i = 0; i < Props.Length; i++)
        //        {
        //            //inserting property values to datatable rows one by one
        //            values[i] = Props[i].GetValue(data, null);
        //        }
        //        dtLstToData.Rows.Add(values);
        //    }

        //    return dtLstToData;
        //}

No comments:

Post a Comment