Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...