Lately I’ve been doing my fair share of client-side libraries around third-party RESTful APIs, for both Windows Phone and Windows 8. If you’ve ever done some REST API integrations before in Asp.NET, WPF or Silverlight, you’ve probably come across the NameValueCollection in System.Collections.Specialized.

Despite not being thread-safe, only accepting keys and values that are of type String, and not supporting LINQ, this class was useful in situations in which you either needed to associate multiple values with a key (which is fairly common when building query strings) or when you needed to perform hash-based lookups. And to be honest, none of those cons really matters. Because you’ll rarely have enough parameters to actually suffer a performance hit (costs due to boxing), and you don’t really care if they're not strongly typed --all those values will be converted to a String before they are sent over the wire anyway.

With this NameValueCollection implementation, whenever I’d need to send a query string with the same key multiple times:  

I would write something like this:

var parameters = new NameValueCollection();  
parameters.Add("profile_ids[]", "cb04e870000010");  
parameters.Add("profile_ids[]", "cb04bb81000067");  
parameters.Add("profile_ids[]", "cb04bbt7300025");  

Furthermore, by setting the GroupByCommaSeparatedValues property you can control whether all the values associated with a specific key should be grouped using the comma separator instead:

parameters.GroupByCommaSeparatedValues = true;  

will now return:[]=cb04e870000010,cb04bb81000067,cb04bbt7300025  

Anyway, this will always get you a properly formatted and encoded query string when the ToString() method on the NameValueCollection is invoked.



Windows Phone , Windows 8 , NameValueCollection

Written by