Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a namevaluecollection

How do I sort a namevaluecollection in alphabetical order? Do I have to cast it to another list first like the sorted list or Ilist or something? If then how do I do that? right now I have all my string in the the namevalucollection variable.

like image 842
zack Avatar asked Nov 04 '10 20:11

zack


People also ask

Is NameValueCollection case sensitive?

The name is case-insensitive.

What is NameValueCollection?

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold multiple string values under a single key.


1 Answers

Preferably use a suitable collection to begin with if it's in your hands. However, if you have to operate on the NameValueCollection here are some different options:

NameValueCollection col = new NameValueCollection();
col.Add("red", "rouge");
col.Add("green", "verde");
col.Add("blue", "azul");

// order the keys
foreach (var item in col.AllKeys.OrderBy(k => k))
{
    Console.WriteLine("{0}:{1}", item, col[item]);
}

// or convert it to a dictionary and get it as a SortedList
var sortedList = new SortedList(col.AllKeys.ToDictionary(k => k, k => col[k]));
for (int i = 0; i < sortedList.Count; i++)
{
    Console.WriteLine("{0}:{1}", sortedList.GetKey(i), sortedList.GetByIndex(i));
}

// or as a SortedDictionary
var sortedDict = new SortedDictionary<string, string>(col.AllKeys.ToDictionary(k => k, k => col[k]));
foreach (var item in sortedDict)
{
    Console.WriteLine("{0}:{1}", item.Key, item.Value);
}
like image 181
Ahmad Mageed Avatar answered Sep 18 '22 19:09

Ahmad Mageed