yield keyword



using System;
using System.Collections;
using System.Collections.Generic;


namespace YieldDemo
{
public static class YieldDemo
{
///
/// Filtrarea unui sir de stringuri cu yield
///
///
///
public static IEnumerable NamesWitchStartsWithALetter(string[] names)
{
foreach ( string name in names )
if ( name.StartsWith ( "A" ) )
yield return name;
}

///
/// crearea unui iterator pentru un numar limitat de patrate perfect
///
///
///
public static IEnumerable<int> Squares(int squaresCount)
{
int sqCounter = 1;
while (sqCounter <= squaresCount)
{
yield return sqCounter * sqCounter;
sqCounter++;
}
}
/// <summary>
/// iterator pentru primele n numere din sirul Fibonacci
/// </summary>
/// <param name="fibLength"></param>
/// <returns></returns>
public static IEnumerable<int> Fibonacci ( int fibLength )
{
if ( fibLength < 0 )
yield break;

if ( fibLength == 0 )
{
yield return 1;
yield break;
}
if ( fibLength == 1 )
{
yield return 1;
yield return 1;
yield break;
}

int first = 1;
int second = 1;
int counter = 1;
yield return 1;
yield return 1;
while ( counter++ < fibLength )
{
int retValue = first + second;
first = second;
second = retValue;
yield return retValue;
}
}
}
}

Comments

Popular posts from this blog

IIS 7.5, HTTPS Bindings and ERR_CONNECTION_RESET

Verify ILogger calls with Moq.ILogger

Table Per Hierarchy Inheritance with Column Discriminator and Associations used in Derived Entity Types