Search code examples
c#.net-2.0

Fastest way to convert DataTable to List using .NET 2.0


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

Solution

  • I can't think of any other optimization

    int count = table.Rows.Count;
    List<MyType> data = new List<MyType>(count);
    
    for(int i = 0 ; i <count; i ++)
    {
        DataRow row = tables.Rows[i];
        data.Add(new MyType((int)row[0], (string)row[1]));  
    }
    
    return data;