星期五, 9月 25, 2009

Dictionary 如何排序

最近在工作上遇到小問題,就是 Dictionary 麼排序,有些高手一看到就很直覺得想,阿就用 Linq to Object 就好啦,10秒鐘搞定..一_一||..話說是沒錯啦,如果有 Linq to Object 這把屠龍刀在手上,管他天皇老子,砍下去就好啦..問題就是,我的環境是 2.0 啦..還是要想一個辦法來解決一下,看code吧..

先貼一下2.0是怎麼苦命的解法..

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "aItem");
s.Add("2", "cItem");
s.Add("3", "bItem");

List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(delegate(KeyValuePair<string, string> firstPair, KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
});

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (KeyValuePair<string, string> myKey in myList)
{
dic.Add(myKey.Key, myKey.Value);
}

foreach (KeyValuePair<string, string> a in dic)
{
Console.WriteLine(a.Key + " " + a.Value);
}

Console.Read();

再貼一下3.5的Linq to Object是怎麼逍遙的隨筆..

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "aItem");
s.Add("2", "cItem");
s.Add("3", "bItem");

var aaaa = s.OrderBy(a => a.Value);
foreach (var a in aaaa)
{
Console.WriteLine(a.Key + " " + a.Value);
}

Console.Read();

客官阿..你說說看阿您說說看阿..^____^||..

參考:
http://msdn.microsoft.com/zh-tw/library/xfhwa508%28VS.80%29.aspx

1 則留言:

匿名 提到...

我可以問一下這是甚麼語言嗎??
怎麼我感覺像是PHP呢?