使用.net 2.0将数据表转换为列表的最快方法

本文关键字:列表 方法 转换 net 数据表 使用 | 更新日期: 2023-09-27 18:18:45

我刚刚发现这篇文章,我们有几乎相同的场景与用户,但我只使用。net 2.0框架,想知道是否有一个更好更快的实现与下面的代码,将数据表转换为列表。

提前感谢。

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

使用.net 2.0将数据表转换为列表的最快方法

我想不出任何其他优化

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;