2010-11-04 113 views
9

如何按字母順序排序namevaluecollection?我是否必須首先將它轉換爲另一個列表,如排序列表或Ilist或其他?如果那我該怎麼做?現在我已將所有字符串放在namevalucollection變量中。對名稱值集合進行排序

回答

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

讓我來試試你的選擇,並得到back..thanks的幫助BTW .. – zack 2010-11-04 21:11:33

+0

作品像魅力!謝謝艾哈邁德。 – zack 2010-11-04 21:34:19

相關問題