How do you convert a DataTable into a generic list?

前端 未结 27 2554
后悔当初
后悔当初 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:45

    You can create a extension function as :

    public static List ToListof(this DataTable dt)
    {
        const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        var columnNames = dt.Columns.Cast()
            .Select(c => c.ColumnName)
            .ToList();
        var objectProperties = typeof(T).GetProperties(flags);
        var targetList = dt.AsEnumerable().Select(dataRow =>
        {
            var instanceOfT = Activator.CreateInstance();
    
            foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
            {
                properties.SetValue(instanceOfT, dataRow[properties.Name], null);
            }
            return instanceOfT;
        }).ToList();
    
        return targetList;
    }
    
    
    var output = yourDataInstance.ToListof();
    

提交回复
热议问题