Search code examples
c#generic-programminggeneric-list

Iterate through Generic Typed List in c#


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;
}

Solution

  • 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;
            }