To find element from list whose values greater than 3.
Exp-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestYieldKeyword
{
class Program
{
static List<int> MyList = new List<int>() {1,2,3,4,5,6,7,8,9 };
static IEnumerable<int> Filter()
{
List<int> temp = new List<int>();
foreach (int i in MyList)
{
if (i > 3)
{
//yield return i;
temp.Add(i);
}
}
return temp;
}
static void Main(string[] args) // Caller
{
foreach (int i in Filter()) // Browses through the list
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Exp-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestYieldKeyword
{
class Program
{
static List<int> MyList = new List<int>() {1,2,3,4,5,6,7,8,9 };
static IEnumerable<int> Filter()
{
List<int> temp = new List<int>();
foreach (int i in MyList)
{
if (i > 3)
{
//yield return i;
temp.Add(i);
}
}
return temp;
}
static void Main(string[] args) // Caller
{
foreach (int i in Filter()) // Browses through the list
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
output- 4,5,6,7,8,9
But this can be achieved by best approach using Yield Keyword.
Yield is used for custom stateful iterations.Without using temporary collections. Using yield keyword controls moves from callie to caller.
exp-
class Program
{
static List<int> MyList = new List<int>() {1,2,3,4,5,6,7,8,9 };
static IEnumerable<int> Filter()
{
foreach (int i in MyList)
{
if (i > 3)
{
yield return i;
}
}
}
static void Main(string[] args) // Caller
{
foreach (int i in Filter()) // Browses through the list
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
4,5,6,7,8,9
No comments:
Post a Comment