How to convert List> to a DataTable

2020-04-08 11:48发布

How would I convert List<List<string>> to a DataTable? I am trying to set the DataSource of a gridview to a List<List<string>> variable.

3条回答
我想做一个坏孩纸
2楼-- · 2020-04-08 12:07
public static DataTable ToDataTable(this List<List<string>> list)
{
    DataTable dt = new DataTable();
    list.First().ForEach(colname => dt.Columns.Add(colname));
    foreach (List<string> row in list.Skip(1))
        dt.Rows.Add(row.ToArray());
    return dt;
}
查看更多
地球回转人心会变
3楼-- · 2020-04-08 12:19

This can easily be done using extension methods.

Add this class to your solution

static class ListExtensions
{
    public static DataTable ToDataTable(this List<List<string>> list)
    {
        DataTable tmp = new DataTable();
        foreach (List<string> row in list)
        {
            tmp.Rows.Add(row.ToArray());
        }
        return tmp;
    }
}

then use the extension method like this:

List<List<string>> myList = new List<List<string>>();
// Fill with values...
DataTable table = myList.ToDataTable();
查看更多
欢心
4楼-- · 2020-04-08 12:27

I would rather set DataSource of the grid to BindableList, which you would perhaps create easier, instead of double nested List, you would have List of Rows (where the Row is business entity represented, for example Customer).

查看更多
登录 后发表回答