Invert Dictionary mappings in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; public static class Extensions { public static Dictionary<V, K> Reverse<K, V>(this IDictionary<K, V> dict) { var inverseDict = new Dictionary<V, K>(); foreach (var kvp in dict) { if (!inverseDict.ContainsKey(kvp.Value)) { inverseDict.Add(kvp.Value, kvp.Key); } } return inverseDict; } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var inverseDict = dict.Reverse(); Console.WriteLine(String.Join(", ", inverseDict)); // [1, A], [2, B], [3, C] } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static Dictionary<V, K> Reverse<K, V>(this IDictionary<K, V> dict) { return dict.ToDictionary(x => x.Value, x => x.Key); } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3} }; var inverseDict = dict.Reverse(); Console.WriteLine(String.Join(", ", inverseDict)); // [1, A], [2, B], [3, C] } } |
That’s all about inverting Dictionary mappings in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)