I have to sort a namevaluecollection(Items usually 5 to 15) Against an enum(having items more than 60). Right now I am using this extension function, Anyone have better idea to write this code....
public static NameValueCollection Sort(this NameValueCollection queryString, Type orderByEnumType, bool excludeZeroValues)
{
NameValueCollection _processedQueryString = HttpUtility.ParseQueryString("");
if (queryString.HasKeys())
{
SortedList<int, KeyValuePair<string, string>> querySortedList = new SortedList<int, KeyValuePair<string, string>>();
string[] enumKeys = Enum.GetNames(orderByEnumType);
int counter = 1000;
foreach (string key in queryString)
{
string value = queryString[key];
if (enumKeys.Contains(key, StringComparer.CurrentCultureIgnoreCase))
{
int order = (int)Enum.Parse(orderByEnumType, key, true);
querySortedList.Add(order, new KeyValuePair<string, string>(key, value));
}
else
{
querySortedList.Add(counter, new KeyValuePair<string, string>(key, value));
counter++;
}
}
foreach (KeyValuePair<int, KeyValuePair<string, string>> kvp in querySortedList)
{
if (!kvp.Value.Value.IsNullOrEmpty() && !kvp.Value.Key.IsNullOrEmpty())
{
if (!excludeZeroValues || kvp.Value.Value != "0")
{
_processedQueryString.Add(kvp.Value.Key, System.Web.HttpUtility.UrlEncode(kvp.Value.Value));
}
}
}
}
return _processedQueryString;
}
This works like this
public enum OrderEnum
{
key1=1,
key2=20,
key3=3,
//note
key4=100,
key5=2,
key6=6,
key7,
key8,
key9
}
public void Test()
{
NameValueCollection col1 = new NameValueCollection();
col1.Add("key1", "value1");
col1.Add("key9", "value1");
col1.Add("key3", "value1");
col1.Add("key5", "value1");
Response.Write(col1.Sort(typeof(OrderEnum)).ToString());
//out put: key1=value1&key5=value1&key3=value1&key9=value1
}
This is should also work
public void Test2()
{
NameValueCollection col1 = new NameValueCollection();
col1.Add("key1", "value1");
col1.Add("key-x", "value1");
col1.Add("key-y", "value1");
col1.Add("key9", "value1");
col1.Add("key3", "value1");
col1.Add("key5", "value1");
col1.Add("key-z", "value1");
Response.Write(col1.Sort(typeof(OrderEnum)).ToString());
//out put: key1=value1&key5=value1&key3=value1&key9=value1&key-x=value1&key-y=value1&key-z=value1
}