This post will discuss how to invert Dictionary mappings in C#.

1. Using foreach loop

The idea is to create a new instance of Dictionary<TValue,TKey> for a given dictionary of type Dictionary<TKey,TValue>. Then use a foreach loop to iterate over the dictionary, and insert each mapping into the new Dictionary in reverse order of its key-value pair. The following code demonstrates this.

Download  Run Code

 
Note that for any repeated values in the given dictionary, the above solution considers the first encountered value and ignores all other values.

2. Using Dictionary<TKey,TValue>.ToDictionary() Method

Another option is to use the Dictionary<TKey,TValue>.ToDictionary() method to accumulate the key-value pairs into a new dictionary in reverse order. Note that this assumes that the reverse mapping is well-defined, and throws System.ArgumentException if the values in the original map are not unique.

Download  Run Code

That’s all about inverting Dictionary mappings in C#.