Recently I was writing some code that interacted with a
third party API for doing searching.
This API would return me a single result object fore each found result for
my search, but the result object it returned me was a dictionary style
object. This object would contain 1-n
different key/value pairs that would contain all sorts of data. After examining the results for a few searches
I realized I only needed a few pieces of data from the result. Like I said before since the result was a
Disctionary object Dictionary<string,
object > I knew that in order to grab all the values out of the object I would have to
implement my own switch statement and look for each key one by one.
As I started to write this switch statement I started to wonder if there was another way of doing this. After some brain storming with a co-worker we decided it could be done using Anonymous Delegates. Below I will show the old way (using switch statements) and the new way (using delegates)
Here is the fake result object model that I will pull the data out of.
Here is the object model that I will populate with the data from the fake result (yes i know, not well formed, but this is a POC after all)
Here is the code needed in order to use a switch statement
Here is the code using the anonymous delegates:
Setting up the needed variables
Building the needed mapper object
Performing the actual mapping
Now, I know that using the switch statement is easy to read and very easy to understand compared to the anonymous delegates, but this was just an fun little exercise to see if there is a different way to do this. I would consider using the anonymous delegate route if my setting actions were simple and if the case block would be very lengthly.
Has anyone else done something similar? Have any suggestions on how to do this better?
03-31-2007 2:44 PM