How to loop through WebHeaderCollection

gusaindpk picture gusaindpk · Jun 22, 2011 · Viewed 24.7k times · Source

How do you loop through a WebHeaderCollection got from HttpWebResponse in windows phone 7 to get keys and values? We've tried Enumerator.Current; with this, we are only getting the keys, not the values. We are doing this to get a redirected URL.

Answer

ony picture ony · Sep 5, 2012

That's an awful collection, I think.

See MSDN sample. I'd prefer this one:

var headers = new System.Net.WebHeaderCollection();
headers.Add("xxx", "yyy");
headers.Add("zzz", "fff");
headers.Add("xxx", "ttt");
for(int i = 0; i < headers.Count; ++i)
{
    string header = headers.GetKey(i);
    foreach(string value in headers.GetValues(i))
    {
        Console.WriteLine("{0}: {1}", header, value);
    }
}

Unfortunately there is no way to get values with order preserving between other headers.

P.S. Linq style (in LINQPad)

var items = Enumerable
                .Range(0, headers.Count)
                .SelectMany(i => headers.GetValues(i)
                    .Select(v => Tuple.Create(headers.GetKey(i), v))
                );
items.Dump();