計算機科学のブログ

LINQ and lambdas - Get Control of your data - IEnumerable interface, GetEnumerator method

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 9(LINQ and lambdas - Get Control of your data)、p.525(Exercise)の解答を求めてみる。

コード

ComicAnalyzer.cs

using System;
using System.Collections;
using System.Collections.Generic;
namespace MyConsoleApp
{
    public class PowersOfTwo: IEnumerable<int>
    {
        public PowersOfTwo()
        {
        }

        public IEnumerator<int> GetEnumerator()
        {
            for (int power = 0; power < Math.Round(Math.Log(int.MaxValue, 2)); power++)
            {
                yield return (int)Math.Pow(2, power);
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

コード

Program.cs

using System;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in new PowersOfTwo())
            {
                Console.WriteLine(item);
            }
        }
    }
}

入出力結果(Terminal, Zsh)

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824