Accessing Row based data in an efficient and maintainable manner - The Code Project - C# Database

This is a nice and simple article about accessing data from a lot of datarows. While using the string index will make the code more readable, using the integer index will make the code faster. The solution? Get the numeric indexes at the beginning of the loop, based on string indexes. Assert the indexes exist for better debugging. Very elegant. Also, check out the user comments, which are pretty good and to the point.

Code example:

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

System.Diagnostics.Debug.Assert(customerIDIndex > -1,
"Database out of sync");
System.Diagnostics.Debug.Assert(customerFirstNameIndex > -1,
"Database out of sync");
System.Diagnostics.Debug.Assert(customerLastNameIndex > -1,
"Database out of sync");

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

Comments

Be the first to post a comment

Post a comment