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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With