星期五, 7月 04, 2014

[C#] 根據 Dictionary 的 value 來進行排序

MVA Twenty C# Questions Explained - [​19 How do I sort a dictionary by value?]
  • LINQ
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));
    }
}
[C#] 根據 Dictionary 的 value 來進行排序-1


  • MVA 課程範例
課程範例是用中斷點並透過區域變數是了解 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));
    }
}

[C#] 根據 Dictionary 的 value 來進行排序-2

  • List 轉為 Dictionary
找資料了解 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));
    }
}
[C#] 根據 Dictionary 的 value 來進行排序-3

1 則留言:

  1. 黑暗大測試過效能的部份,
    http://blog.darkthread.net/post-2011-10-20-linq-search-performance-issue.aspx

    回覆刪除