【C#】ラムダ式おぼえがき


ラムダ式で文字数が5文字以下のnamesが何件あるか調べる

Sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {

        static void Main(string[] args)
        {
            List<String> names = new List<string>
            {
                "shimakaze",
                "amatsukaze",
                "kongo",
                "kuma",
                "tama",
            };

            // ラムダ式
            Func<string, bool> predicate = str => str.Length < 5;

            int count = CountList(names, predicate);
            Console.WriteLine(count);

        }

        private static int CountList(List<string> names, Func<string, bool> predicate)
        {
            int count = 0;
            foreach (string str in names)
            {
                if (predicate(str))
                {
                    count++;
                }
            }
            return count;
        }
    }
}