Created
June 21, 2019 17:37
-
-
Save dterracino/ec23aad8f0b3aef79aeba9fee5fa0b5f to your computer and use it in GitHub Desktop.
Yield C# Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Source: https://www.c-sharpcorner.com/article/top-7-least-known-but-important-c-sharp-features/ | |
| // Check the two Filter() methods; note the difference - no temp collection needed | |
| // YIELD PROVIDES STATEFUL ITERATION! | |
| class Employee | |
| { | |
| public string Name { get; set; } | |
| public int Salary { get; set; } | |
| } | |
| class Program | |
| { | |
| static List<Employee> Employees = new List<Employee>() | |
| { | |
| new Employee{ Name="Tom", Salary=12000}, | |
| new Employee{ Name="Harry", Salary=15000}, | |
| new Employee{ Name="Sam", Salary=10000}, | |
| new Employee{ Name="Mike", Salary=25000}, | |
| new Employee{ Name="Bob", Salary=22000}, | |
| new Employee{ Name="Raj", Salary=18000}, | |
| }; | |
| static void Main(string[] args) | |
| { | |
| PrintData(); | |
| } | |
| static void PrintData() | |
| { | |
| foreach (var emp in FilterWYield()) | |
| { | |
| Console.WriteLine(emp.Name); | |
| } | |
| foreach (var emp in FilterSimple()) | |
| { | |
| Console.WriteLine(emp.Name); | |
| } | |
| } | |
| static IEnumerable<Employee> FilterWYield() | |
| { | |
| foreach (var item in Employees) | |
| { | |
| if (item.Salary >= 20000) | |
| yield return item; | |
| } | |
| } | |
| static IEnumerable<Employee> FilterSimple() | |
| { | |
| List<Employee> emps = new List<Employee>(); | |
| foreach (var item in Employees) | |
| { | |
| if (item.Salary >= 20000) | |
| emps.Add(item); | |
| } | |
| return emps; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment