Convert DataSet to List

后端 未结 11 2214
一整个雨季
一整个雨季 2020-12-04 08:39

Here is my c# code

Employee objEmp = new Employee();
List empList = new List();
foreach (DataRow dr in ds.Tables[0].Rows)
{
          


        
11条回答
  •  盖世英雄少女心
    2020-12-04 08:56

    Here's extension method to convert DataTable to object list:

        public static class Extensions
        {
            public static List ToList(this DataTable table) where T : new()
            {
                IList properties = typeof(T).GetProperties().ToList();
                List result = new List();
    
                foreach (var row in table.Rows)
                {
                    var item = CreateItemFromRow((DataRow)row, properties);
                    result.Add(item);
                }
    
                return result;
            }
    
            private static T CreateItemFromRow(DataRow row, IList properties) where T : new()
            {
                T item = new T();
                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(System.DayOfWeek))
                    {
                        DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                        property.SetValue(item,day,null);
                    }
                    else
                    {
                        if(row[property.Name] == DBNull.Value)
                            property.SetValue(item, null, null);
                        else 
                            property.SetValue(item, row[property.Name], null); 
                    }
                }
                return item;
            }
        }
    

    usage:

    List lst = ds.Tables[0].ToList();
    

    @itay.b CODE EXPLAINED: We first read all the property names from the class T using reflection
    then we iterate through all the rows in datatable and create new object of T,
    then we set the properties of the newly created object using reflection.

    The property values are picked from the row's matching column cell.

    PS: class property name and table column names must be same

提交回复
热议问题