It can be tedious to iterate over a generic Dictionary in C#, especially if the Dictionary contains complex types. The values you’re interested in are properties of the iteration variable. I never know what to name the iteration variable (here I name it “pair”), which is an indicator this code is clumsy.

Make it easier on yourself by using C#’s Tuple Deconstruction language feature. First, write an extension method for the generic KeyValuePair class.

Or, instead of writing the extension method, you can add a reference to my ErikTheCoder.ServiceContract package and add a using ErikTheCoder.ServiceContract; statement.

Then rewrite your foreach loop with more a compact, yet readable, syntax.

Leave a Reply

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