How do you convert a DataTable into a generic list?

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

    lPerson = dt.AsEnumerable().Select(s => new Person()
            {
                Name = s.Field("Name"),
                SurName = s.Field("SurName"),
                Age = s.Field("Age"),
                InsertDate = s.Field("InsertDate")
            }).ToList();
    

    Link to working DotNetFiddle Example

    using System;
    using System.Collections.Generic;   
    using System.Data;
    using System.Linq;
    using System.Data.DataSetExtensions;
    
    public static void Main()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("SurName", typeof(string));
        dt.Columns.Add("Age", typeof(int));
        dt.Columns.Add("InsertDate", typeof(DateTime));
    
        var row1= dt.NewRow();
        row1["Name"] = "Adam";
        row1["SurName"] = "Adam";
        row1["Age"] = 20;
        row1["InsertDate"] = new DateTime(2020, 1, 1);
        dt.Rows.Add(row1);
    
        var row2 = dt.NewRow();
        row2["Name"] = "John";
        row2["SurName"] = "Smith";
        row2["Age"] = 25;
        row2["InsertDate"] = new DateTime(2020, 3, 12);
        dt.Rows.Add(row2);
    
        var row3 = dt.NewRow();
        row3["Name"] = "Jack";
        row3["SurName"] = "Strong";
        row3["Age"] = 32;
        row3["InsertDate"] = new DateTime(2020, 5, 20);
        dt.Rows.Add(row3);
    
        List lPerson = new List();
        lPerson = dt.AsEnumerable().Select(s => new Person()
        {
            Name = s.Field("Name"),
            SurName = s.Field("SurName"),
            Age = s.Field("Age"),
            InsertDate = s.Field("InsertDate")
        }).ToList();
    
        foreach(Person pers in lPerson)
        {
            Console.WriteLine("{0} {1} {2} {3}", pers.Name, pers.SurName, pers.Age, pers.InsertDate);
        }
    }   
    
    public class Person
    {
        public string Name { get; set; }
        public string SurName { get; set; }
        public int Age { get; set; }
        public DateTime InsertDate { get; set; }
    }
    

    }

提交回复
热议问题