プログラミングとかブログ

Unity/C#/SRPGStudio/RPGツクールMVの情報とかその他気になったことを調べて書きます。

Where(x => x)の意味

Where(x => x)の意味:コレクション内の値のうちtrueのものを探す

Where内は条件文なので(x => x)だと(x => x == true)を意味します。
そしてWhere(x => !x)は(x => x == false)を表します。
以下のコードを見ると動きがわかると思います。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("出力結果");
            Console.WriteLine();

            Console.Write("リスト:");
            List<bool> boolList = new List<bool>() { true, false, false, true, true, true };
            foreach (var boolValue in boolList)
                Console.Write(boolValue + ",");

            Console.WriteLine();
            Console.WriteLine("Where(x=>x)で検索したTrueの数:" + boolList.Where(x => x).Count().ToString());

            Console.WriteLine();

            Console.Write("リスト:");
            boolList = new List<bool>() { true, false, false, true, true, true };
            foreach (var boolValue in boolList)
                Console.Write(boolValue + ",");

            Console.WriteLine();
            Console.WriteLine("Where(x=>!x)で検索したFalseの数:" + boolList.Where(x => !x).Count().ToString());

            Console.ReadLine();
        }
    }
}


出力結果

リスト:True,False,False,True,True,True,
Where(x=>x)で検索したTrueの数:4

リスト:True,False,False,True,True,True,
Where(x=>!x)で検索したFalseの数:2



パッと見混乱することが多いので備忘録を兼ねて。