Topic: Iterate from 0 to 20 (excluding 20), output each element that is traversed to, and put all numbers greater than 2 in a IEnumerable to return
Answer 1: (I used to do this often)
Static ienumerable<int> Withnoyield ()
{
ilist<int> list = new list<int> ();
for (int i = 0; i < i++)
{
Console.WriteLine (i.ToString ());
if (i > 2)
List. ADD (i);
}
return list;
}
Answer 2: (Since C # 2.0 we can still do this)
Static ienumerable<int> Withyield ()
{
for (int i = 0; i < i++)
{
Console.WriteLine (i.ToString ());
if (i > 2)
yield return i;
}
}
What output would I get if I tested it with the following code?
Test 1:
Test Withnoyield ()
static void Main ()
{
Withnoyield ();
Console.ReadLine ();
}
Test Withyield ()
static void Main ()
{
Withyield ();
Console.ReadLine ();
}
Test 2:
Test Withnoyield ()
static void Main ()
{
foreach (int i in Withnoyield ())
{
Console.WriteLine (i.ToString ());
}
Console.ReadLine ();
}
Test Withyield ()
static void Main ()
{
foreach (int i in Withyield ())
{
Console.WriteLine (i.ToString ());
}
Console.ReadLine ();
}