Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Reversing a Dictionary in LINQ and C#
WhatsApp
Mike Gold
15y
56.3
k
0
0
25
Blog
Someone recently gave me the task to figure out how to reverse a dictionary. Basically they wanted to switch the keys and values so the values become the keys and the keys become the values. Instead of trying to figure it out myself, I googled reverse dictionary and found it on
stackoverflow
. You simply say
var
newDictionary = oldDictionary.ToDictionary(x => x.Value, x => x.Key);
if you think you may have duplicates then use:
var
newDictionary = oldDictionary.GroupBy(pair => pair.Value).Select(group => group.First()).ToDictionary(pair => pair.Value, pair => pair.Key);
If you just want to search values linearly to find a key using the value(for smaller dictionaries) use:
var
result = (
from
val
in
oldDictionary.Keys
where
valToFind == oldDictionary[val]
select
val).First();
Up Next
How To Create Pagination Using LINQ In C#
Ebook Download
View all
Printing in C# Made Easy
Read by 22.3k people
Download Now!
Learn
View all
Membership not found