ASP.Net/C# convert NameValueCollection to IDictionary?

DJGray picture DJGray · Apr 24, 2013 · Viewed 9.1k times · Source

I’m trying to help my son upgrade a web site I built for him last year. He wants to implement Amazon Simple Pay. I’m SO close to getting it, but have an error that I don’t know how to address. It’s an ASP.Net site done in C#. I am an untrained (self-taught) developer, so speak in simple terms, please. ;-)

In ASP.Net, it is not legal to have a Form within a Form, and I need to do a Form POST. There is a pretty slick tutorial online that shows how to make this happen. The URL is http://weblogs.asp.net/hajan/archive/2011/04/20/amazon-simple-pay-in-asp-net.aspx if you’re interested in seeing it.

The transaction has to be “signed” and Amazon provides a SignatureUtils class to accomplish this. In that class, I’m calling this:

public static string signParameters(IDictionary<String, String> parameters, String key, String HttpMethod, String Host, String RequestURI, String algorithm) 

What’s killing me is the IDictionary parameter. What I have to pass it is this ListParams NameValueCollection that I built with:

public System.Collections.Specialized.NameValueCollection ListParams = new System.Collections.Specialized.NameValueCollection();

It’s giving me the error below, because it can’t convert the NameValueCollection to an IDictionary. I tried explicitly converting it, but no joy. How can I solve this?

Error: Argument 1: cannot convert from 'System.Collections.Specialized.NameValueCollection' to 'System.Collections.Generic.IDictionary<string,string>'

Answer

mattytommo picture mattytommo · Apr 24, 2013

You can do that by using Cast:

IDictionary<string, string> dict = ListParams.Cast<string>()
    .ToDictionary(p => p, p => ListParams[p]);