LINQ and lambdas - Get control of your data - enumerable class, IEnumerable interface
Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 9(LINQ and lambdas - Get control of your data)、p.525(Exercise)の解答を求めてみる。
コード
Program.cs
using ConsoleApp1;
PowersOfTwo powersOfTwo = new PowersOfTwo();
foreach (int item in powersOfTwo)
{
Console.WriteLine(item);
}
PowersOfTwo.cs
using System.Collections;
namespace ConsoleApp1;
public class PowersOfTwo : IEnumerable<int>
{
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();
}
}
入出力結果(Terminal, Zsh)
% dotnet run
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
%