Thursday, April 23, 2009

Find a key by its value in a NameValueCollection

While I was working one of my samples, I came across a nice problem: "How do I get a key from a NameValueCollection by its value?"
Assume the following declaration:

NameValueCollection nvc = new NameValueCollection { { "a", "abc" }, { "b", "bcd" }, { "c", "cde" } };

Well, I can try to explain why I needed it but I assure you it wasn’t so important. In fact, the only added value of this sample was me finding a nice solution to this problem :)

Back to the point, there was, of course, the strait forward solution of iterating on the list and checking for a match on each value but that was too ugly even for a sample.
So, why not recruit LINQ to the rescue?
A small attempt made me realize that though the collection implement IEnumerable, the enumeration works only on the keys so still no cookies for me.

Couple of more hits on the head with a club made me remembered that I have Extension methods in my arsenal. I know I had previously warned about in this post.
Well, I guess it can now come in handy.

public static class SampleExtensions
public static IEnumerable<KeyValuePair<string, string>> GetPairs(this NameValueCollection coll)
if (coll == null)
throw new ArgumentNullException("throw something here");
return coll.Cast<string>().Select(key => new KeyValuePair<string, string>(key, coll[key]));

Nothing fancy here. The cast was done so I could use the select method.

var result = (from pair in nvc.GetPairs() where (string.Compare( pair.Value,"abc")==0) select pair.Key);

result.ToList<string>().ForEach(str => Console.WriteLine(str));

Now for the usage. The search is now done on a KeyValuePair and now I have access to the value in each pair.
The last line prints the result to the console and there you have it.

I'm sure there was a good reason why this feature was left on the drawing board.

No comments:

Post a Comment