Answers for "convert datatable list to model list c# explicit"

C#
0

c# convert list t to datatable

public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
Posted by: Guest on April-25-2022
0

convert list to datatable c#

Public Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
         Dim table As New DataTable()
         Dim fields() As FieldInfo = GetType(T).GetFields()
         For Each field As FieldInfo In fields
            table.Columns.Add(field.Name, field.FieldType)
         Next
         For Each item As T In list
            Dim row As DataRow = table.NewRow()
            For Each field As FieldInfo In fields
                  row(field.Name) = field.GetValue(item)
            Next
           table.Rows.Add(row)
         Next
         Return table
End Function
Posted by: Guest on March-08-2022

C# Answers by Framework

Browse Popular Code Answers by Language