C# 使用.NET 2.0将数据表转换为列表的最快方法
我刚刚发现了这一点,我们的用户情况几乎相同,但我只使用.NET2.0框架,我想知道下面的代码是否有更好更快的实现,将datatable转换为list 提前谢谢C# 使用.NET 2.0将数据表转换为列表的最快方法,c#,.net-2.0,C#,.net 2.0,我刚刚发现了这一点,我们的用户情况几乎相同,但我只使用.NET2.0框架,我想知道下面的代码是否有更好更快的实现,将datatable转换为list 提前谢谢 namespace DataTableToListTest { public partial class MainForm : Form { // Just a sample class class MyType { private int
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;
}
}
}
命名空间DataTableToListTest
{
公共部分类主窗体:窗体
{
//只是一个示例类
类MyType
{
私营机构国际办事处;;
私人字符串(u bar),;
公共MyType(int-foo、字符串栏)
{
_foo=foo;
_巴=巴;
}
公共int-Foo
{
获取{return\u foo;}
设置{u foo=value;}
}
公共字符串栏
{
获取{return\u bar;}
设置{u bar=value;}
}
}
公共表格(
{
初始化组件();
dataGridView1.DataSource=GetDataSource();
}
列表GetDataSource()
{
DataTable=GetTable();
对于(int i=0;i<5000;i++)
表.行.添加(i,“行”+i);
列表数据=新列表(table.Rows.Count);
foreach(table.Rows中的DataRow行)
添加(新的MyType((int)行[0],(string)行[1]);
返回数据;
}
//假设此方法查询数据库
数据表GetTable()
{
DataTable=新的DataTable();
表.列.添加(“Foo”,typeof(int));
表.Columns.Add(“Bar”,typeof(string));
返回表;
}
}
}
我想不出任何其他优化
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;
int count=table.Rows.count;
列表数据=新列表(计数);
对于(int i=0;您当前的代码是否存在性能瓶颈?老实说,我没有在我的应用程序中尝试过这一点。使用此方法在数据库中查询的示例对象是员工数据。我只是使用此MyType类进行演示…除非有问题,否则您需要code@yonan2236例如你应该经常尝试一些c在试图找到更快的东西之前,先对它进行测量。@Jon:这是值得注意的。LINQ实际上在引擎盖后面工作(循环)类似的东西,对吗?