开发者

sorting a namevaluecollection

How do I sort a namevaluecollection in alphabetical order? Do I have to cast it to another lis开发者_JAVA百科t 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.


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);
}


See this question: How to sort NameValueCollection using a key in C#?

...which suggests using a SortedDictionary

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜