アットウィキロゴ

csharp_list_sortcustom

ListのSortをデリゲートを用いてカスタマイズしてみる

デリゲートを用いてSortをカスタムしたサンプルを残す。

       class Word
       {
           private string phrase = "";
           private string furigana = "";
           private int cnt = 0;

           /// <summary>
           /// 語句
           /// </summary>
           public string Phrase
           {
               get { return this.phrase; }
           }
           /// <summary>
           /// ふり仮名
           /// </summary>
           public string Furigana
           {
               get { return this.furigana; }
           }
           /// <summary>
           /// 出現数
           /// </summary>
           public int Count
           {
               set { this.cnt = value; }
               get { return this.cnt; }
           }
           /// <summary>
           /// コンストラクタ
           /// </summary>
           public Word(string phrase, string furigana)
           {
               this.phrase = phrase;
               this.furigana = furigana;
           }
       }

       static void Main(string[] args)
       {
           List<Word> list = new List<Word>();
           string search = "";

           Word word1 = new Word("語句", "ごく");
           word1.Count = 5;
           list.Add(word1);

           Word word2 = new Word("単語", "たんご");
           word2.Count = 3;
           list.Add(word2);

           Word word3 = new Word("連続", "れんぞく");
           word3.Count = 20;
           list.Add(word3);

           // ソート前の結果を出力
           Console.WriteLine("----------ソート前----------");
           foreach (Word word in list)
           {
               Console.WriteLine(word.Furigana + "\t" + word.Phrase + "\t" + word.Count);
           }
           // 出現数で降順にソート
           list.Sort(
               delegate(Word x, Word y)
               {
                   return y.Count - x.Count;
               }
           );
           Console.WriteLine("----------ソート後----------");
           // ソート後の結果を出力
           foreach (Word word in list)
           {
               Console.WriteLine(word.Furigana + "\t" + word.Phrase + "\t" + word.Count);
           }
       }
最終更新:2009年02月13日 14:34