Sunday, April 26, 2009

C# 4.0 - Collection of links

I've just came across this great post at Bogdan Brinzarea’s blog.
The post contains plenty of links on each of the new features in the new framework.


Friday, April 24, 2009

//Magic. do not touch

I've stumbled upon this hilarious post in stackoverflow under the title of "What is the best comment in source code you have ever encountered?".

As the title implies, this was my favorite!
I also like this one as well :)

// Dear maintainer:
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning\
// to the next guy:
// total_hours_wasted_here = 16

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.