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
This is where ToDictionary makes life easy. I changed my signature to take a dictionary
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);