LoginSignup
16
16

More than 5 years have passed since last update.

C#におけるデリゲートの記法の進化、クエリ式について

Last updated at Posted at 2015-05-07

以下の記事がわかりやすかったので勉強がてらコードを書いてみた
【LINQの前に】ラムダ式?デリゲート?Func?な人へのまとめ【知ってほしい】

歴史をすっとばして紹介すると

このコードが


using System;
using System.Collections.Generic;

namespace DelegateSamples
{
    class MainClass
    {
        //デリゲートの定義
        public delegate bool predicate(string str);

        //デリゲートの参照先メソッド
        public static bool IsLengthLessThan5(string str)
        {
            return str.Length < 5;
        }

        //アイテムを判定するメソッド
        private static int CountList(List<string> names,predicate pre)
        {
            int count = 0;

            foreach (string item in names)
            {
                if (pre(item)) {
                    // 真ならカウンタをインクリメント
                    count++;
                }
            }
            return count;
        }

        public static void Main (string[] args)
        {
            //リストの定義
            List<string> names = new List<string>
            {
                "Taro",
                "Jiro",
                "Saburo",
                "Umeko",
                "Takeko",
                "Matsuko",
            };

            //デリゲートの型のメソッドを変数化する
            //これにより引数にメソッドを渡す事ができる
            predicate IsLengthCheck = MainClass.IsLengthLessThan5;
            int count = CountList(names, IsLengthCheck);
            Console.WriteLine(count.ToString());
        }
    }
}

こうなる


using System;
using System.Collections.Generic;
using System.Linq;

namespace DelegateTest04
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<string> names = new List<string>
            {
                "Taro",
                "Jiro",
                "Saburo",
                "Umeko",
                "Takeko",
                "Matsuko",
            };

            Console.WriteLine(names.Count((x) => x.Length < 5).ToString());
        }
    }
}

短っ!!

リンク先の記事は「LINQの前に」と断っているためLINQの事は書いていませんがLINQを理解する上で重要な事が丁寧に書いてあります。

コメント適当な感じですが、一応サンプルコードも置きますので学習の一助になれば幸いです

疑問

Multicastどこいってもうたんや...
匿名メソッドでも+=できるけど戻り値は最後のメソッドだけ帰ってくる

このあたりかな、そのうち書こう

16
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16