我有一个拥有100,000+ 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];
//process the dataRow
}
方法2:
for (int c = 0; c < dsDataSet.Tables["dtTableName"].Rows.Count; c++)
{
var theRow = dsDataSet.Tables["dtTableName"].Rows[c];
//process the dataRow
}
答案 0 :(得分:1)
值得注意的是,访问单元的最直接方式是通过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;
// ...
}
甚至可以通过dynamic
跳过该类型:
string region = "North";
foreach(var row in conn.Query("select * from [Foo] where Region = @region",
new { region })) // ^^^ note no <Foo> here
{
// here "row" is dynamic, but still works; not quite as direct as a
// POCO object, though
int id = row.Id; // <=== note we can't use `var` here or the
string name = row.Name; // variables would themselves be "dynamic"
// ...
}