Jun 13, 2009

C# yield example


private void Form1_Load(object sender, EventArgs e)
{
int i = 0;
string[] arr = new string[] { "bob1", "can", "bob2", "boB3", "everyday", "Bob4" };

foreach (string str in FindBobs(arr))
{
Console.WriteLine(++i + ". " + str);
}
}
static IEnumerable<string> FindBobs(string[] arr)
{
foreach (string str in arr)
{
if (str.Equals("bob3", StringComparison.OrdinalIgnoreCase))
yield break;
if (str.StartsWith("bob", StringComparison.OrdinalIgnoreCase))
yield return str;
}
}

Output:
1. bob1
2. bob2

If the "yeild break" statement is commented the output is:
1. bob1
2. bob2
3. boB3
4. Bob4

No comments:

Post a Comment