foreach

using System;
using System.Collections.Generic;
public class Program
{
static void Main()
{
*// Part 1: compute powers of two with the exponent of 30.*
foreach (int value in ComputePower(2, 30))
{
Console.WriteLine(value);
}
}
public static IEnumerable<int> ComputePower(int number, int exponent)
{
*// Part 2: continue loop until the exponent count is reached.*
*// ... Yield the current result.*
int exponentNum = 0;
int numberResult = 1;
while (exponentNum < exponent)
{
*// Multiply the result.*
numberResult *= number;
exponentNum++;
*// Return the result with yield.*
yield return numberResult;
}
}
}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

using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
var s1 = Stopwatch.StartNew();
*// Version 1: use foreach with array.*
for (int i = 0; i < _max; i++)
{
if (Method1(numbers) != 300)
{
throw new Exception();
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
*// Version 2: use foreach with yield keyword.*
for (int i = 0; i < _max; i++)
{
if (Method2(numbers) != 300)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(*"0.00 ns"*));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(*"0.00 ns"*));
}
static int Method1(int[] numbers)
{
*// Sum with simple statements.*
int sum = 0;
foreach (int number in numbers)
{
sum += number * 2;
}
return sum;
}
static int Method2(int[] numbers)
{
*// Use yield return to get multiplied numbers and then sum those.*
int sum = 0;
foreach (int number in GetNumbers(numbers))
{
sum += number;
}
return sum;
}
static IEnumerable<int> GetNumbers(int[] numbers)
{
*// Return all numbers multiplied.*
foreach (int number in numbers)
{
yield return number * 2;
}
}
} 3.84 ns inline expression
50.68 ns yield return

IEnumerable

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Jan 16, 2024 (edit).