1

我有一个包含 100,000 多个 DataRow 的数据表。哪种方法访问集合更快?有没有更快的方法来处理行集合?方法一:

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 
}

方法二:

for (int c = 0; c < dsDataSet.Tables["dtTableName"].Rows.Count; c++)
{
    var theRow = dsDataSet.Tables["dtTableName"].Rows[c];
    //process the dataRow 
}
4

1 回答 1

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"
    // ...
}
于 2013-04-12T07:30:02.013 回答