IDataRecord Fields to Dictionary Extension Method

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<string, object> FieldsToDictionary(this IDataRecord dataRecord)        {            Dictionary<string, object> fieldBag = new Dictionary<string, object>(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<string, object> 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.

About Me: Paul Kinlan

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.