Article 6KXMY CodeSOD: They Key To Dictionaries

CodeSOD: They Key To Dictionaries

by
Remy Porter
from The Daily WTF on (#6KXMY)

It's incredibly common to convert objects to dictionaries/maps and back, for all sorts of reasons. Jeff's co-worker was tasked with taking a dictionary which contained three keys, "mail", "telephonenumber", and "facsimiletelephonenumber" into an object representing a contact. This was their solution:

foreach (string item in _ptAttributeDic.Keys){string val = _ptAttributeDic[item];switch (item){ case "mail": if (string.IsNullOrEmpty(base._email)) base._email = val; break; case "facsimiletelephonenumber": base._faxNum = val; break; case "telephonenumber": base._phoneNumber = val; break;}}

Yes, we iterate across all of them to find the ones that we want. The dictionary in question is actually quite large, so we spend most of our time here looking at keys we don't care about, to find the three we do. If only there were some easier way, some efficient option for finding items in a dictionary by their name. If only we could just fetch items by their key, then we wouldn't need to have this loop. If only.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments