Iterate through Generic Typed List in c#

770 Views Asked by At

I am trying to iterate through the generic type object list, i am able to get the properties of the object however unable to get the values from properties of each instance of the object. Here's how my code looks like: I want create a function that will convert any list passed to it and convert it into DataTable.

--DataObject

public class StudentDo
{
     public int Id {get;set}
     public string Name {get;set}
}

--Generic Data Access Object

public DataTable ConvertListToDataTable(List<T> list, string tableName = "")
{
     var type = typeof(T);
     var properties = type.GetProperties().ToList();
     DataTable dt = new DataTable(tableName);
     properties.ForEach(x =>
     {
         dt.Columns.Add(x.Name);
     });

     // i don't know how shall i pull data from each instance of List<T>.
     return dt;
}
2

There are 2 best solutions below

3
Nikhil Patil On BEST ANSWER

Iterate over the list and insert against each column using reflection -

public static DataTable ConvertListToDataTable<T>(List<T> list, string tableName = "")
        {
            var type = typeof(T);
            var properties = type.GetProperties().ToList();
            DataTable dt = new DataTable(tableName);
            properties.ForEach(x =>
            {
                dt.Columns.Add(x.Name);
            });
            foreach (var item in list)
            {
                var dataRow = dt.NewRow();
                properties.ForEach(x =>
                {
                    dataRow[x.Name] = x.GetValue(item, null);
                });
                dt.Rows.Add(dataRow);
            }
            return dt;
        }
0
user8426192 On

This is what I use:

    public DataTable ToDataTable<T>(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;
    }