对namevaluecollection进行排序

时间:2010-11-04 20:40:45

标签: c# .net sorting sortedlist namevaluecollection

如何按字母顺序对namevaluecollection进行排序?我是否必须先将其转换为另一个列表,如排序列表或Ilist或其他?如果那么我该怎么做?现在我在namevalucollection变量中包含了所有字符串。

2 个答案:

答案 0 :(得分:13)

如果它在您手中,最好使用合适的系列。但是,如果您必须对NameValueCollection进行操作,则可以使用以下选项:

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

答案 1 :(得分:0)

相关问题