How do you convert a DataTable into a generic list?

前端 未结 27 2877
后悔当初
后悔当初 2020-11-22 17:04

Currently, I\'m using:

DataTable dt = CreateDataTableInSomeWay();

List list = new List(); 
foreach (DataRow dr in dt.Rows)
{
          


        
27条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 17:44

    I have added some modification to the code from this answer (https://stackoverflow.com/a/24588210/4489664) because for nullable Types it will return exception

    public static List DataTableToList(this DataTable table) where T: new()
    {
        List list = new List();
        var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
            {
                PropertyInfo = propertyInfo,
                Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
            }).ToList();
    
        foreach (var row in table.Rows.Cast())
        {
            T obj = new T();
            foreach (var typeProperty in typeProperties)
            {
                object value = row[typeProperty.PropertyInfo.Name];
                object safeValue = value == null || DBNull.Value.Equals(value)
                    ? null
                    : Convert.ChangeType(value, typeProperty.Type);
    
                typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
            }
            list.Add(obj);
        }
        return list;
    }
    

提交回复
热议问题