Replace SortedDictionary with LINQ query

With LINQ.Flickr it is quite necessary to get signature on parameters in order to do authenticated flickr photo get. As with the signature, it has to be sorted by parameter then to be hashed by MD5. Previously, I used to use SortedDictionary dictionary to do so, but thinking a little bit I learned that we actually don't need SortedDictionary anymore after we have LINQ. May be that's why the product team at Microsoft removed SortedDictionary from stripped down version of .net that comes with SilverLight.

Now, off to code, lets say I want 10 photos from my photo stream in flickr, to achieve that  I would simply write

var query = (from photo in context.Photos
            where photo.ViewMode == ViewMode.Owner
            select photo).Take(10);

Behind the scene, it will first try to authenticate me, if I am not already then it will try to do it and finally it will make an authenticated call to get my photos from my flickr account. Using SortedDictionary, the sorting of signature items used to be done on the fly but the overhead is that on every new item inserted in the dictionary due to each parameter of REST call, it runs the sort logic. This is of course a waste of processor speed. So, I replaced all the lines that look like

IDictionary<string, string> sortedSigItems 
= new SortedDictionary<string, string>();

with

IDictionary<string, string> sigItems = new Dictionary<string, string>();

Finally, inside my GetSignature method at BaseRepository of LINQ.Flickr I added the following lines, before final toString stuff.

var query = from sigItem in sigItems
            orderby sigItem .Key ascending
            select sigItem.Key + sigItem .Value;

// do the rest with sorted list.

The whole thing is much pleasing with LINQ query and less processor intensive.So next time when you think about sorting, think about LINQ first :-)

Have fun!!!

Continued with comparison in part 2 of this post.

kick it on DotNetKicks.com

2 Comments

  • Do you have some test results which show that the Linq query is faster? I would be very intrested in seeing those :)

  • Ok, LINQ uses a comparator to sort its items when asending and decending is used. Now, for SortedDictionary every item you insert it runs through a sort logic and it gets expensive as the number of parameter increases. This kind of increasing perfomance degradation can be minimized by the method i have said above, but i will try to add comparison with my old and new dll for sorted dictonary effect.

Comments have been disabled for this content.