Performance 访问DataTable/DataRowsCollection的更快方法是什么?
我有一个datatable,有100000+个DataRow。哪种方法访问集合更快? 有没有更快的方法来处理行集合? 方法1:Performance 访问DataTable/DataRowsCollection的更快方法是什么?,performance,datatable,dataset,Performance,Datatable,Dataset,我有一个datatable,有100000+个DataRow。哪种方法访问集合更快? 有没有更快的方法来处理行集合? 方法1: var rows= dsDataSet.Tables["dtTableName"].Rows; int rowCount = dsDataSet.Tables["dtTableName"].Rows.Count; for (int c = 0; c < rowCount; c++) { var theRow = rows[c];
var rows= dsDataSet.Tables["dtTableName"].Rows;
int rowCount = dsDataSet.Tables["dtTableName"].Rows.Count;
for (int c = 0; c < rowCount; c++)
{
var theRow = rows[c];
//process the dataRow
}
var rows=dsDataSet.Tables[“dtTableName”].rows;
int rowCount=dsDataSet.Tables[“dtTableName”].Rows.Count;
对于(int c=0;c
方法2:
for (int c = 0; c < dsDataSet.Tables["dtTableName"].Rows.Count; c++)
{
var theRow = dsDataSet.Tables["dtTableName"].Rows[c];
//process the dataRow
}
for(int c=0;c
值得注意的是,访问单元格的最直接方式是通过数据列
索引器;数据实际上存储在列中,而不是行中(否:真的)
比如:
var table = dataSet.Tables["dtTableName"];
// HERE: fetch the DataColumn of those you need, for example:
var idCol = table.Columns["Id"];
var nameCol = table.Columns["Name"];
// now loop
foreach(DataRow row in table.Rows)
{
var id = (int)row[idCol];
var name = (string)row[nameCol];
// ...
}
但是,坦率地说,如果您希望获得最佳性能,我会首先说“不要使用DataSet
/DataTable
”。这实际上是一个非常复杂的模型,设计成各种各样的灵活模式,具有更改跟踪、规则执行等功能。如果您想要快速,我会使用POCO和类似“dapper”的东西,例如:
public class Foo {
public int Id {get;set;}
public string Name {get;set;}
}
...
string region = "North";
foreach(var row in conn.Query<Foo>("select * from [Foo] where Region = @region",
new { region })) // <=== simple but correct parameterisation
{
// TODO: do something with row.Id and row.Name, which are direct
// properties of the Foo row returned
var id = row.Id;
var name = row.Name;
// ...
}
值得注意的是,访问单元格的最直接方式是通过
DataColumn
索引器;数据实际上存储在列中,而不是行中(否:真的)
比如:
var table = dataSet.Tables["dtTableName"];
// HERE: fetch the DataColumn of those you need, for example:
var idCol = table.Columns["Id"];
var nameCol = table.Columns["Name"];
// now loop
foreach(DataRow row in table.Rows)
{
var id = (int)row[idCol];
var name = (string)row[nameCol];
// ...
}
但是,坦率地说,如果您希望获得最佳性能,我会首先说“不要使用DataSet
/DataTable
”。这实际上是一个非常复杂的模型,设计成各种各样的灵活模式,具有更改跟踪、规则执行等功能。如果您想要快速,我会使用POCO和类似“dapper”的东西,例如:
public class Foo {
public int Id {get;set;}
public string Name {get;set;}
}
...
string region = "North";
foreach(var row in conn.Query<Foo>("select * from [Foo] where Region = @region",
new { region })) // <=== simple but correct parameterisation
{
// TODO: do something with row.Id and row.Name, which are direct
// properties of the Foo row returned
var id = row.Id;
var name = row.Name;
// ...
}
我的目标是更快地访问数据表(目前我无法逃避)。你能进一步启发我吗?通过列访问datatable是否比通过名称或索引访问datatable快一些?@DioPhung?是的,稍微有点。对不起,伙计们,但我看不出有什么不同。在从索引切换到列之后,我丢失了同样的时间来分配数据行。我的目标是更快地访问数据表(目前我无法逃避它)。你能进一步启发我吗?通过列访问datatable是否比通过名称或索引访问datatable快一些?@DioPhung?是的,稍微有点。对不起,伙计们,但我看不出有什么不同。在从索引切换到列之后,数据行的分配也会丢失同样的时间。