如何在C#中将DataTable转换为对象类型List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12834059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:37:02  来源:igfitidea点击:

How to convert DataTable to object type List in C#

c#datatablegeneric-list

提问by Rashedul Alam

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

我想在 C# 中转换DataTableList<object>。这是我的代码。但它不起作用。请帮我

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

在此处输入图片说明

采纳答案by Neeraj Kumar Gupta

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

或者如果你仍然想要,List<object>那么就这样做

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);
}

回答by abhishek

The DataRow need to be created before adding it to the DataRow collection.

在将 DataRow 添加到 DataRow 集合之前,需要先创建它。

For instance,

例如,

DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        var dr = dt.NewRow();
        dr[0] = "1";
        dr[1] = "AAA";
        dt.Rows.Add(dr);
        ... likewise

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

Now the List should hold the Rows. Let me know if it works.

现在列表应该包含行。让我知道它是否有效。

回答by CRoshanLG

I hope what you are trying to do is insert the objects in the data table (which probably are returned from a query) in to a List.

我希望您要做的是将数据表中的对象(可能从查询中返回)插入到列表中。

public List<object> ShowMessage2(DataTable dtInput)
    {
        List<object> objectList = new List<object>();

        foreach(DataRow dr in dtInput.Rows)
        {
            MyObj newObj = new MyObj();
            newObj.ID = Convert.ToInt32(dr["ID"]);  // Beware of the possible conversion errors due to type mismatches
            newObj.Name = dr["Name"].ToString();

            objectList.Add(newObj);
        }
        return objectList;
    }

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


Just saw your addition to the question! I can't understand why you try to generate a list if your intention is just to display the data in a gird view, which you can do in a single line!!!

刚刚看到您对问题的补充!如果您的目的只是在网格视图中显示数据(您可以在一行中完成),我无法理解为什么要尝试生成列表!!!

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");

dataGridView1.DataSource = dt; // THIS IS ALL U NEED! Just bind the DataTable to the grid as data source!