アットウィキロゴ

csharp_list_findindexcustom

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

Listの要素がクラスだったりすると、FindIndex等の検索がそのまま行うことができない。
ので、デリゲートを用いてFindIndexをカスタムしたサンプルを残す。

       class Word
       {
           private string phrase = "";
           private string furigana = "";

           /// <summary>
           /// 語句
           /// </summary>
           public string Phrase
           {
               get { return this.phrase; }
           }
           /// <summary>
           /// ふり仮名
           /// </summary>
           public string Furigana
           {
               get { return this.furigana; }
           }
           /// <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("語句", "ごく");
           list.Add(word1);

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

           search = "単語";
           int idx = list.FindIndex(
               delegate(Word x)
               {
                   if (x.Phrase == search) return true;
                   else return false;
               }
           );
           Console.WriteLine(search+"のFindIndexの結果:" + idx);

           search = "うにゃ";
           idx = list.FindIndex(
               delegate(Word x)
               {
                   if (x.Phrase == search) return true;
                   else return false;
               }
           );
           Console.WriteLine(search+"のFindIndexの結果:" + idx);
       }

[出力結果]
       単語のFindIndexの結果:1
       うにゃのFindIndexの結果:-1
最終更新:2009年02月13日 14:21