I just found this post, we have almost the same scenario with the user but I only use .NET 2.0 framework and would like to know if there's a better and faster implementation with the codes below, converting datatable to list.
Thanks in advance.
namespace DataTableToListTest
{
public partial class MainForm : Form
{
// Just a sample class
class MyType
{
private int _foo;
private string _bar;
public MyType(int foo, string bar)
{
_foo = foo;
_bar = bar;
}
public int Foo
{
get { return _foo; }
set { _foo = value; }
}
public string Bar
{
get { return _bar; }
set { _bar = value; }
}
}
public MainForm()
{
InitializeComponent();
dataGridView1.DataSource = GetDataSource();
}
List<MyType> GetDataSource()
{
DataTable table = GetTable();
for (int i = 0; i < 5000; i++)
table.Rows.Add(i, "Row " + i);
List<MyType> data = new List<MyType>(table.Rows.Count);
foreach (DataRow row in table.Rows)
data.Add(new MyType((int)row[0], (string)row[1]));
return data;
}
// Suppose this method queries the database
DataTable GetTable()
{
DataTable table = new DataTable();
table.Columns.Add("Foo", typeof(int));
table.Columns.Add("Bar", typeof(string));
return table;
}
}
}