How do you convert a DataTable into a generic list?

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

    Converting DataTable to Generic Dictionary

    public static Dictionary<object,IList<dynamic>> DataTable2Dictionary(DataTable dt)
    {
        Dictionary<object, IList<dynamic>> dict = new Dictionary<dynamic, IList<dynamic>>();
    
        foreach(DataColumn column in dt.Columns)
        {
            IList<dynamic> ts = dt.AsEnumerable()
                                  .Select(r => r.Field<dynamic>(column.ToString()))
                                  .ToList();
            dict.Add(column, ts);
        }
        return dict;
    }
    
    0 讨论(0)
  • 2020-11-22 17:48

    If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List<DataRow> instead of just IEnumerable<DataRow> you can call Enumerable.ToList:

    IEnumerable<DataRow> sequence = dt.AsEnumerable();
    

    or

    using System.Linq;
    ...
    List<DataRow> list = dt.AsEnumerable().ToList();
    
    0 讨论(0)
  • 2020-11-22 17:49

    With C# 3.0 and System.Data.DataSetExtensions.dll,

    List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();
    
    0 讨论(0)
  • 2020-11-22 17:50

    Use Extension :

    public static class Extensions
    {
        #region Convert Datatable To List
        public static IList<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            IList<T> result = new List<T>();
    
            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }
            return result;
        }
        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                property.SetValue(item, row[property.Name], null);
            }
            return item;
        }
        #endregion
    }
    
    0 讨论(0)
  • 2020-11-22 17:55

    You could use

    List<DataRow> list = new List<DataRow>(dt.Select());
    

    dt.Select() will return all rows in your table, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill your list with.

    0 讨论(0)
  • 2020-11-22 17:55

    Use System.Data namespace then you will get .AsEnumerable().

    0 讨论(0)
提交回复
热议问题