Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DataTable to object type List in C# [closed]

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

like image 883
Rashedul Alam Avatar asked Nov 27 '22 21:11

Rashedul Alam


1 Answers

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/

like image 188
Neeraj Kumar Gupta Avatar answered Nov 29 '22 11:11

Neeraj Kumar Gupta