1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LINQの遅延評価を使って、好きなタイミングで式を評価する

Posted at

LINQの遅延評価の勉強のために下記コードを実行してみました。

main.cs
using System.IO;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr1 = new int [5];
        int[] arr2 = {1, 2, 3, 4, 5};
        
        Console.Write("declare linq\n");
        int mulNum = 1;
        var fnc = arr2.Select((x, i) => {
            arr1[i] = x * mulNum;
            string strOut = arr1[i].ToString() + " ";
            if(i == arr2.Count() - 1){
                strOut += "\n";
            }
            Console.Write(strOut);
            return x;
        });
        
        mulNum = 2;
        fnc.ToArray();

        mulNum = 1;
        fnc.ToArray();
    }
}

実行結果

declare linq
2 4 6 8 10 
1 2 3 4 5 

LINQのSelectで書いた式は、ToArray()をつけたタイミングで評価されることが確認できました。

1
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?