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.
The name is case-insensitive.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With