2010-11-04 26 views
9

¿Cómo puedo ordenar un nombre de colección en orden alfabético? ¿Tengo que lanzarlo a otra lista primero como la lista ordenada o Ilist o algo así? Entonces, ¿cómo hago eso? ahora tengo toda mi cadena en la variable namevalucollection.ordenando un namevaluecollection

Respuesta

13

Es preferible utilizar una colección adecuada para empezar si está en sus manos. Sin embargo, si tiene que operar en el NameValueCollection aquí hay algunas opciones diferentes:

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

voy a tratar de conseguir sus opciones y back..thanks por la ayuda .. por cierto funciona como – zack

+0

¡un encanto! gracias Ahmad. – zack