How to Swap Keys and Values in a Dictionary in C#


How to Swap Keys and Values in a Dictionary in C# ?

Answer

To swap keys and values in a dictionary in C#, you can use a `foreach` loop to iterate through the original dictionary and add each key-value pair to a new dictionary with the key and value swapped. This allows you to create a new dictionary where the keys and values are swapped.



✐ Examples

1 Swapping Keys and Values in a Dictionary Using a `foreach` Loop

We can swap keys and values in a dictionary in C# using a `foreach` loop. This example demonstrates how to declare and initialize a dictionary, use a `foreach` loop to swap the keys and values, and print the resulting dictionary.

For example,

  1. We start by including the necessary namespace: using System.Collections.Generic;.
  2. We declare and initialize a dictionary named originalDict with integer keys and string values.
  3. We declare an empty dictionary named swappedDict to store the swapped key-value pairs.
  4. We use a `foreach` loop to iterate through the original dictionary and add each key-value pair to the new dictionary with the key and value swapped.
  5. We print the resulting dictionary.

C# Program

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare and initialize a dictionary
        Dictionary<int, string> originalDict = new Dictionary<int, string>
        {
            {1, "One"},
            {2, "Two"},
            {3, "Three"}
        };

        // Declare an empty dictionary to store the swapped key-value pairs
        Dictionary<string, int> swappedDict = new Dictionary<string, int>();

        // Use a foreach loop to swap the keys and values
        foreach (var kvp in originalDict)
        {
            swappedDict[kvp.Value] = kvp.Key;
        }

        // Print the resulting dictionary
        Console.WriteLine("Swapped dictionary:");
        foreach (var kvp in swappedDict)
        {
            Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
        }
    }
}

Output

Swapped dictionary:
Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3

2 Swapping Keys and Values in a Dictionary with Duplicate Values

We can swap keys and values in a dictionary with duplicate values in C# by checking for duplicates and handling them appropriately. This example demonstrates how to declare and initialize a dictionary with duplicate values, use a `foreach` loop to swap the keys and values while handling duplicates, and print the resulting dictionary.

For example,

  1. We start by including the necessary namespace: using System.Collections.Generic;.
  2. We declare and initialize a dictionary named originalDict with integer keys and string values, including duplicate values.
  3. We declare an empty dictionary named swappedDict to store the swapped key-value pairs.
  4. We use a `foreach` loop to iterate through the original dictionary, check for duplicate values, and add each key-value pair to the new dictionary with the key and value swapped.
  5. We print the resulting dictionary.

C# Program

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare and initialize a dictionary with duplicate values
        Dictionary<int, string> originalDict = new Dictionary<int, string>
        {
            {1, "One"},
            {2, "Two"},
            {3, "One"}
        };

        // Declare an empty dictionary to store the swapped key-value pairs
        Dictionary<string, List<int>> swappedDict = new Dictionary<string, List<int>>();

        // Use a foreach loop to swap the keys and values
        foreach (var kvp in originalDict)
        {
            if (!swappedDict.ContainsKey(kvp.Value))
            {
                swappedDict[kvp.Value] = new List<int>();
            }
            swappedDict[kvp.Value].Add(kvp.Key);
        }

        // Print the resulting dictionary
        Console.WriteLine("Swapped dictionary:");
        foreach (var kvp in swappedDict)
        {
            Console.WriteLine("Key: {0}, Values: {1}", kvp.Key, string.Join(", ", kvp.Value));
        }
    }
}

Output

Swapped dictionary:
Key: One, Values: 1, 3
Key: Two, Values: 2

Summary

In this tutorial, we learned How to Swap Keys and Values in a Dictionary in C# language with well detailed examples.




More C# Dictionaries Tutorials

  1. How to create an Empty Dictionary in C# ?
  2. How to create a Dictionary with Initial Key-Value Pairs in C# ?
  3. How to Print a Dictionary in C# ?
  4. How to Add a Key-Value Pair to a Dictionary in C# ?
  5. How to Set a Default Value for a Key in a Dictionary in C# ?
  6. How to Update the Value for a Key in a Dictionary in C# ?
  7. How to Check if a Dictionary is Empty in C# ?
  8. How to Check if a Key Exists in a Dictionary in C# ?
  9. How to Check if a Value Exists in a Dictionary in C# ?
  10. How to Get the Value Associated with a Key in a Dictionary in C# ?
  11. How to Remove a Key-Value Pair from a Dictionary in C# ?
  12. How to Remove Key-Value Pairs from a Dictionary Based on Values in C# ?
  13. How to Clear all Key-Value Pairs from a Dictionary in C# ?
  14. How to Iterate over Keys in a Dictionary in C# ?
  15. How to Iterate over Values in a Dictionary in C# ?
  16. How to Iterate over Entries (Key-Value Pairs) in a Dictionary in C# ?
  17. How to Get the Size (Number of Key-Value Pairs) of a Dictionary in C# ?
  18. How to Convert a Dictionary to an Array of Keys in C# ?
  19. How to Convert a Dictionary to an Array of Values in C# ?
  20. How to Convert a Dictionary to an Array of Key-Value Pairs in C# ?
  21. How to Merge Two Dictionaries in C# ?
  22. How to Clone a Dictionary in C# ?
  23. How to Check if Two Dictionaries are Equal in C# ?
  24. How to Sort a Dictionary by Keys in C# ?
  25. How to Sort a Dictionary by Values in C# ?
  26. How to Filter a Dictionary Based on Keys in C# ?
  27. How to Filter a Dictionary Based on Values in C# ?
  28. How to Reduce Values in a Dictionary to a Single Value in C# ?
  29. How to Convert an Array of Key-Value Pairs to a Dictionary in C# ?
  30. How to Convert a Dictionary to a JSON String in C# ?
  31. How to Convert a JSON String to a Dictionary in C# ?
  32. How to Swap Keys and Values in a Dictionary in C# ?
  33. How to Create a Dictionary of Dictionaries in C# ?
  34. How to Iterate Over a Dictionary of Dictionaries in C# ?