MVA Twenty C# Questions Explained - [19 How do I sort a dictionary by value?]
static void Main(string[] args)
{
Dictionary<string, int?> dic = new Dictionary<string, int?>();
dic.Add("Two", 2);
dic.Add("Zero", 0);
dic.Add("Five", null);
dic.Add("Three", 3);
dic.Add("One", 1);
dic.Add("Four", 4);
Dictionary<string, int?> result = dic.OrderBy(Data => Data.Value).ToDictionary(keyvalue => keyvalue.Key, keyvalue => keyvalue.Value);
foreach (KeyValuePair<string,int?> kvp in result)
{
Console.WriteLine(string.Format("Key - Value:{0} - {1}", kvp.Key, kvp.Value));
}
}
課程範例是用中斷點並透過區域變數是了解 sorted 內資料排序,改寫為直接顯示出來
static void Main(string[] args)
{
Dictionary<string, string> diction = new Dictionary<string, string>();
diction.Add("3", "three");
diction.Add("1", "one");
diction.Add("5", "five");
diction.Add("2", "two");
List<KeyValuePair<string, string>> sortList = diction.ToList();
var sorted = from entry in diction orderby entry.Value ascending select entry;
foreach (KeyValuePair<string, string> kvp in sorted)
{
Console.WriteLine(string.Format("Key - Value:{0} - {1}",kvp.Key,kvp.Value));
}
}
找資料了解 ToDictionary() 時,學的這例子還不錯,紀錄下來
static void Main(string[] args)
{
List<string> listBooks = new List<string>
{
"Visual Studio 2013" ,
"Visual Studio 2010" ,
"Visual Studio 2008" ,
"Visual Studio 2005"
};
int indexvalue = 0;
Dictionary<string, string> booksDictionary = listBooks.ToDictionary
(
keyvalue => "book_" + (indexvalue++).ToString()
);
foreach (KeyValuePair<string, string> kvp in booksDictionary)
{
Console.WriteLine(string.Format("ID:{0};書名:{1}", kvp.Key, kvp.Value));
}
}
黑暗大測試過效能的部份,
回覆刪除http://blog.darkthread.net/post-2011-10-20-linq-search-performance-issue.aspx