值得注意的是,访问单元格最直接的方法是通过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"
// ...
}