LoginSignup
1
1

ラムダ式にif文を使用する

Last updated at Posted at 2023-04-18

ラムダ式の基本

ラムダ式の中でif文は使用できないと思っていたのですが、実際には使用することができました。
(はじめは「使用できない」という記事を投稿しましたが、親切な方からのご指摘により内容を180°修正いたしました)

まずは基本を確認。
ラムダ式は下の2つの形式を取ることができる。

式形式
() => expression
ステートメント形式
() => { sequence-of-statements }
式(expresssion)
評価されて値を返す。評価の結果を持つため、他の式の中で使用したり、文の一部として使用できる。
文(statement)
実行されるのみで値を返さない。変数の宣言・代入、制御構文(if、for、while)が文に当たる。

式は値を返す。
文は値を返さない。

ラムダ式にif文を使用する

if文
List<int> list = new List
List<int> result = list.Where( x =>
{
    if (x % 2 == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}).ToList();

3項演算子を使用する方法もある

3項演算子を使用する
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
List<int> result = list.Where( x => x % 2 == 0 ? true : false ).ToList();
// 上の例は単純な例であり、通常は下のように書く。(良い例が思いつかず...)
List<int> result2 = list.Where( x => x % 2 == 0 ).ToList();
1
1
4

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
1
1