Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 506
Babu Avatar asked Dec 01 '22 10:12

Babu


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

like image 148
ZorgoZ Avatar answered Dec 04 '22 09:12

ZorgoZ