|
IDataRecord Fields To Dictionary Extension Method
By Paul Kinlan
Expert Author
Article Date: 2007-12-20
I have never been a fan of directly passing IDataRecords, or IDataReaders for that matter, about the place to get simple field values out.
Therefore, with the introduction of C# 3.0 and Extension Methods, I thought it would be cool to write (and share) a simple implementation of some code that I use to convert the IDataRecord Field data to an Dictionary<string, object> object.
namespace Kinlan.Data.Extensions
{
public static class DataExtensions
{
public static Dictionary FieldsToDictionary(this IDataRecord dataRecord)
{
Dictionary fieldBag = new Dictionary(dataRecord.FieldCount);
if (dataRecord != null)
{
for (int fieldIdx = 0; fieldIdx < dataRecord.FieldCount; fieldIdx++)
{
string name = dataRecord.GetName(fieldIdx);
object value = dataRecord[fieldIdx];
fieldBag.Add(name, value);
}
}
return fieldBag;
}
}
}
It is quite simple really and nothing too complex.
A place where it can be used it Windows Workflow. If you are injecting parameters into your Workflow instance you need to pass a Dictionary in, well now you can (if you desired) simply convert a IDataReader/IDataRecord object into with the following simple piece of code:
WorkflowInstance instance = runtime.CreateWorkflow(typeof(_WorkflowClass_), dataReaderInstance.FieldsToDictionary());
This code should be used sparingly, for instance if you wanted a very high performance access to the field data, you might as well stay on the IDataRecord.
Comments
About the Author:
Paul Kinlan is the author of the popular C#, .Net Framework blog. Paul is an Analyst Developer working in Southport, England. Paul has several years experience developing and designing massively scalable enterprise systems on UNIX and Windows based architectures.
|