// sortbyvalue.cs using System; using System.Net; using System.Text.RegularExpressions; using System.Collections.Generic; class DictionarySortByValue { static void makeDict(Dictionary dict) { string html; // HTMLの取得 using (WebClient wc = new WebClient()) { html = wc.DownloadString("http://www.atmarkit.co.jp/"); } // 単語に分割して、各単語の出現頻度をカウント foreach (string s in Regex.Split(html, "\\W")) { string word = s.Trim(); if (word != "") { if (dict.ContainsKey(word)) { dict[word]++; } else { dict[word] = 1; } } } } static void Main() { Dictionary dict = new Dictionary(); makeDict(dict); List> sorted = sortByValue(dict); // sorted.Reverse(); // 逆順にする場合 foreach (KeyValuePair kvp in sorted) { Console.WriteLine(kvp.Key + ":" + kvp.Value); } // 出力例: // a:542 // td:394 // 0:328 // width:289 // tr:284 // …… } static List> sortByValue(Dictionary dict) { List> list = new List>(dict); // Valueの大きい順にソート list.Sort( delegate(KeyValuePair kvp1, KeyValuePair kvp2) { return kvp2.Value - kvp1.Value; }); return list; } } // コンパイル方法:csc sortbyvalue.cs