Loving ToDictionary

I love ToDictionary()! It allows me to easily transform disparate data into a common format I can use to send to methods making those methods less coupled and more readily reusable. Let me provide an example.

I have a method that needs to process header values of web request and do certain things based on their values, the signature looks something like this:

public ComService  GetServiceBasedOnSource(IServiceFactory factory, 
                                           HttpRequestHeaders headers, 
                                           string tokenValue)

I was given a requirement to have the same processing occur based of off query string values if headers are not available. I was passing headers directly to my method, however, so wasn’t sure what to do. I figured I could pull out common code and have two methods, one with signature for headers and one with signature for query string parameter values, which is turns out are a collection of KeyValuePair if you use the Request.GetQueryNameValuePairs() method. When thinking about this I realized if I pulled the common code out I’d have to transform the different input into something I could process, so if I was going to alter data why not let caller do it and have one method with a signature that wasn’t dependent on headers or keyvaluepairs?

This is where ToDictionary makes life easy. I changed my signature to take a dictionary instead of headers or keyvaluepairs and toDictionary makes this transformation a snap. My method now looks like:

public ComService  GetServiceBasedOnSource(IServiceFactory factory, 
                                           Dictionary<string, string> dictionary, 
                                           string tokenValue)

And to use it I just ToDictionary the inputs:

public ComService  GetServiceBasedOnSource(factory, 
                                           Request.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault()),
                                           token);

or 

public ComService  GetServiceBasedOnSource(factory, 
                                           Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value), 
                                           token);

Leave a Reply

Your email address will not be published. Required fields are marked *