Friday, September 16, 2011

Converting SqlReader rows to Hashtable array


Sometimes you don't want to use LINQ or some other domain type structure to hold your rows of data.  Here's a quick way to convert your SqlReader rows to a Hashtable array and it works for pretty much any row.  


Just keep in mind this doesn't work well if you've got thousands of rows to return, but it's great if you know your dataset is small and want something that's easy to use and ensures that the rows are stored by field name.
 public Hashtable SqlReaderRowToHash(SqlDataReader reader)  
 {  
   Hashtable results = new Hashtable();  
   // read each column  
   for (int i = 0; i < reader.FieldCount; i++)  
   {  
     string orgFieldName = reader.GetName(i);  
     string fieldName = orgFieldName;  
     // append index to name if field appears multiple times  
     for (int index = 0; ; index++)  
     {  
       // the first item does not get an index  
       if (index == 0)  
       {  
         // leave the fieldname as is  
         if (results.ContainsKey(fieldName) == false) break;  
       }  
       else  
       {  
         // update the fieldname  
         fieldName = String.Format("{0}{1}", orgFieldName, index);  
         // use this name if it doesn't exist already  
         if (results.ContainsKey(fieldName) == false) break;  
       }  
     }  
     // add the field to the hashtable  
     results.Add(fieldName, reader[i] == DBNull.Value ? null : reader[i]);  
   }  
   // return the results  
   return results;  
 }  

No comments: