c#代码风格——采用合适的方法访问DataTable里的记录

来源:互联网 发布:我那个是网络服务器 编辑:程序博客网 时间:2024/05/02 22:42

 1.存储过程返回的表结构确定,不会发生改变,直接通过索引访问——高效

foreach(DataRow row in table.Rows)
{
    customer 
= new Customer();
    customer.ID 
= (Int32)row[0];
    customer.FirstName 
= row[1].ToString();
    customer.LastName 
= row[2].ToString();
}

2.返回的表结构经常发生变化,采用如下方式访问

 

int customerIDIndex = table.Columns.IndexOf("customerID");
int customerFirstNameIndex = table.Columns.IndexOf("firstName");
int customerLastNameIndex = table.Columns.IndexOf("lastName");

foreach(DataRow row in table.Rows)
{
    customer 
= new Customer();
    
if(customerIDIndex > -1)
        customer.ID 
= (Int32)row[customerIDIndex];
    
if(customerFirstNameIndex > -1)
        customer.FirstName 
= row[customerFirstNameIndex].ToString();
    
if(customerLastNameIndex > -1)  
        customer.LastName 
= row[customerLastNameIndex].ToString();
}