Search code examples
c#dictionaryswap

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


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..


Solution

  • 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();
        }
      }
    }