Search code examples
c#datatablegeneric-list

How to convert DataTable to object type List in C#


I want to convert DataTable to List<object> in C#. Here is my code. But it is not working. Please help me

public List<object> ShowMessage()
{
    List<object> obj = new List<object>();

    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Name");

    dt.Rows.Add("1","AAA");
    dt.Rows.Add("2", "BBB");
    dt.Rows.Add("3", "CCC");

    foreach (DataRow dr in dt.Rows)
    {
        obj.Add(dr);
    }

    return obj;
}

This is the Error--

enter image description here


Solution

  • If you have any Typed DataType for list object something like this

    public class MyObj
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
    

    then you can do like this

    private List<MyObj> test(DataTable dt)
    {
           
        var convertedList = (from rw in dt.AsEnumerable()
            select new MyObj() 
            {
                ID = Convert.ToInt32(rw["ID"]),
                Name = Convert.ToString(rw["Name"])
            }).ToList();
    
        return convertedList;
    }
    

    or if you still want List<object> then do like this

    private List<object> GetListByDataTable(DataTable dt)
    {
    
        var reult = (from rw in dt.AsEnumerable()
            select new
            {
                Name = Convert.ToString(rw["Name"]),
                ID = Convert.ToInt32(rw["ID"])
            }).ToList();
    
        return reult.ConvertAll<object>(o => (object)o);
    }
    

    or follow this it has generic resolution too https://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/