how to swap keys into values and values into key in a dictionary

Viewed 4837

guys i want to swap the keys and values in dictionary

my dictionary loook like this

public static void Main(string[] args)
{
Dictionary<int,int> dic = new Dictionary<int,int>{{1,10}, {2, 20}, {3, 30}};
}

now iam printing the values form dictionary

 foreach (KeyValuePair<int, int> kvp in dic)
{

    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            Console.ReadKey();
}

in display i got this

Key = 1, Value = 10
Key = 2, Value = 20
Key = 3, Value = 30

i want to swap values between key and value.. after swapping the answer should be like this

Key = 10, Value = 1
Key = 20, Value = 2
Key = 30, Value = 3

i did lambda expression it changed but i need some other method to do..

3 Answers

Supposing the values are unique, this can work:

var dic = new Dictionary<int,int>{{1,10}, {2, 20}, {3, 30}};

var dic2 = dic.ToDictionary(x => x.Value, x=> x.Key);

It won't actually swap the sides, you will get a new dictionary.

Here is an extension so you can do:

Dictionary<int, int> newDic = oldDic.SwapKeysAndValues();



    /// <summary>
    /// Take a dictionary and make the values the keys and the keys the values
    /// </summary>
    /// <typeparam name="K">The original dictionary key type</typeparam>
    /// <typeparam name="V">The original value type</typeparam>
    /// <param value="dictionary<K, V>"></param>
    /// <returns>Dictionary<V, K></returns>
    public static Dictionary<V, K> SwapKeysAndValues<K, V>(this Dictionary<K, V> original)
    {
        Dictionary<V, K> result = new Dictionary<V, K>();
        foreach (V value in original.Values.Distinct())
        {
            result.Add(value, original.First(x => x.Value.Equals(value)).Key);
        }

        // optional
        //if(original.Count > result.Count)
        //{
        //  throw new Exception("Duplicate value ignored ");
        //}


        return result;
    }

I think you will understand the below code:

namespace Swap
{
public class Class1
{
    public SortedDictionary<string, string> names;

    public void BeforeSwaping()
    {
        Console.WriteLine("Before Swapping: ");
        Console.WriteLine();
        names = new SortedDictionary<string, string>();
        names.Add("Sonoo", "srinath");
        names.Add("Perer", "mahesh");
        names.Add("James", "ramesh");
        names.Add("Ratan", "badri");
        names.Add("Irfan", "suresh");
        names.Add("sravan", "current");
        foreach (KeyValuePair<string, string> item in names)
        {

            Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);

        }
        Console.WriteLine();
    }

    public void AfterSwaping()
    {
        Console.WriteLine("After Swapping: ");
        Console.WriteLine();
        var key = names.Keys;
        var val = names.Values;

        string[] arrayKey = new string[key.Count];
        string[] arrayVal = new string[val.Count];
        int i = 0;
        foreach (string s in key)
        {
            arrayKey[i++] = s;
        }
        int j = 0;
        foreach (string s in val)
        {
            arrayVal[j++] = s;
        }
        names.Clear();
        //Console.WriteLine(arrayVal[0] + " " + arrayKey[0]);
        for (int k = 0; k < (arrayKey.Length + arrayVal.Length) / 2; k++)
        {
            names.Add(arrayVal[k], arrayKey[k]);
        }
        foreach (KeyValuePair<string, string> s in names)
        {
            Console.WriteLine("key:"+s.Key + ", "+"value:" + s.Value);
        }
    }
    public static void Main(string[] args)
    {
        Class1 c = new Class1();
        c.BeforeSwaping();
        c.AfterSwaping();
        Console.ReadKey();
    }
  }
}
Related