Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

08 Aug 2008

Presenting NameValueCollectionHelper

Here are a couple functions that i find extremely useful when i’m working with a NameValueCollection

public static class NameValueCollectionHelper
{
	public static void AddOrIgnoreOnDuplicateKey(NameValueCollection collection, NameValueCollection nameValuesToAdd);
	public static void AddOrReplaceOnDuplicateKey(NameValueCollection collection, NameValueCollection nameValuesToAdd);
	public static void AddOrCombineOnDuplicateKey(NameValueCollection collection, NameValueCollection nameValuesToAdd);
	public static void AddOrFailOnDuplicateKey(NameValueCollection collection, NameValueCollection nameValuesToAdd);
}

All these methods provide a specific scenario of the more generic Add operation

public static class NameValueCollectionHelper
{
	private static Dictionary<duplicateKeyBehavior, Action<nameValueCollection, NameValueCollection>> duplicateKeyBehaviors;

	static NameValueCollectionHelper()
	{
		duplicateKeyBehaviors = new Dictionary<duplicateKeyBehavior, Action<nameValueCollection, NameValueCollection>>();
		duplicateKeyBehaviors.Add(DuplicateKeyBehavior.Ignore, NameValueCollectionHelper.AddOrIgnoreOnDuplicateKey);
		duplicateKeyBehaviors.Add(DuplicateKeyBehavior.Replace, NameValueCollectionHelper.AddOrReplaceOnDuplicateKey);
		duplicateKeyBehaviors.Add(DuplicateKeyBehavior.Combine, NameValueCollectionHelper.AddOrCombineOnDuplicateKey);
		duplicateKeyBehaviors.Add(DuplicateKeyBehavior.Fail, NameValueCollectionHelper.AddOrFailOnDuplicateKey);
	}

	public static void Add(NameValueCollection collection, NameValueCollection nameValuesToAdd, DuplicateKeyBehavior duplicateKeyBehavior)
	{
		duplicateKeyBehaviors[duplicateKeyBehavior](collection, nameValuesToAdd);
	}
}

You should already know that the source is available at BeTimvwFramework.