How do you convert a DataTable into a generic list?

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

    This worked for me: Need at least .Net Framework 3.5, Code below displays DataRow turned to Generic.IEnumerable, comboBox1 has been used for a better illustration.

    using System.Linq;
    
    DataTable dt = new DataTable();            
    dt = myClass.myMethod();                 
    List<object> list = (from row in dt.AsEnumerable() select (row["name"])).ToList();
    comboBox1.DataSource = list;
    
    0 讨论(0)
  • 2020-11-22 17:56

    The Easiest way of Converting the DataTable into the Generic list of class

    using Newtonsoft.Json;

    var json = JsonConvert.SerializeObject(dataTable);
    var model = JsonConvert.DeserializeObject<List<ClassName>>(json);
    
    0 讨论(0)
  • 2020-11-22 17:56

    If anyone want's to create custom function to convert datatable to list

    class Program
    {
        static void Main(string[] args)
        {
            DataTable table = GetDataTable();
            var sw = new Stopwatch();
    
            sw.Start();
            LinqMethod(table);
            sw.Stop();
            Console.WriteLine("Elapsed time for Linq Method={0}", sw.ElapsedMilliseconds);
    
            sw.Reset();
    
            sw.Start();
            ForEachMethod(table);
            sw.Stop();
            Console.WriteLine("Elapsed time for Foreach method={0}", sw.ElapsedMilliseconds);
    
            Console.ReadKey();
        }
    
        private static DataTable GetDataTable()
        {
            var table = new DataTable();
            table.Columns.Add("ID", typeof(double));
            table.Columns.Add("CategoryName", typeof(string));
            table.Columns.Add("Active", typeof(double));
    
            var rand = new Random();
    
            for (int i = 0; i < 100000; i++)
            {
                table.Rows.Add(i, "name" + i,  rand.Next(0, 2));
            }
            return table;
        }
    
        private static void LinqMethod(DataTable table)
        {
            var list = table.AsEnumerable()
                .Skip(1)
                .Select(dr =>
                    new Category
                    {
                        Id = Convert.ToInt32(dr.Field<double>("ID")),
                        CategoryName = dr.Field<string>("CategoryName"),                      
                        IsActive =
                                dr.Field<double>("Active") == 1 ? true : false
                    }).ToList();
        }
        private static void ForEachMethod(DataTable table)
        {
            var categoryList = new List<Category>(table.Rows.Count);
            foreach (DataRow row in table.Rows)
            {
                var values = row.ItemArray;
                var category = new Category()
                {
                    Id = Convert.ToInt32(values[0]),
                    CategoryName = Convert.ToString(values[1]),                   
                    IsActive = (double)values[2] == 1 ? true : false
                };
                categoryList.Add(category);
            }
        }
    
        private class Category
        {
            public int Id { get; set; }
            public string CategoryName { get; set; }
            public bool IsActive { get; set; }
        }
    }
    

    If we execute above code, Foreach method finishes in 56ms while linq one takes 101ms ( for 1000 records). So Foreach method is better to use. Source:Ways to Convert Datatable to List in C# (with performance test example)

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