I'm new to Programming. I would like to implement a program with a yield keyword
. So That, I have created a new List
and ask the user to enter the list values through the console.
After that, I have implemented the foreach
to that list. And Checked the condition, "specific expected string" is present in the list or not with the yield keyword.
My Expectation:
- Loop through the existing list.
- Check that "TamilSelvi" is present inside the List with the help of "yield" keyword.
- Finally, return the matched string
My Implementation:
- I have created a list.
- set the Capacity of that list into 6.
- Get the input for the user through the console.
Finally, Check that the user entered lists values having the "TamilSelvi" or not with the help of yield.
using System;
using System.Collections.Generic;
using System.Collections;
namespace yield_Keyword_in_C_Sharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of Yield Keyword in C# with
List");
Console.WriteLine();
// Create a List
Listnames = new List ();
names.Capacity = 6;
Console.WriteLine("Get the Input From the User");
Console.WriteLine();
//Get the List Input From the User
foreach (string n in names)
{
string temp = Console.ReadLine();
if (temp.Length != 0 && temp != " " && temp != " ")
{
names.Add(temp);
temp = string.Empty;
}
}
//Print the List values entered by the user in the Console Window
Console.WriteLine("Print the Values Entered by the User");
Console.WriteLine();
foreach (string na in names)
{
Console.WriteLine(na);
}
Console.WriteLine();
Console.WriteLine("Get the TamilSelvi in above list with the help
of yield keyword");
display(names);
void display(Listwords) // display method implementation
{
foreach (string word in words)
{
if (word == "TamilSelvi") yield return word;
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
Expected Result:
Implementation of Yield Keyword in C# with List
Get the Input From the User
Thirunavukkarasu
TamilSelvi
Vennilla
Sabarinathan
Muthuprakash
Mutharasan
Print the Values Entered by the User
Thirunavukkarasu
TamilSelvi
Vennilla
Sabarinathan
Muthuprakash
Mutharasan
Get the TamilSelvi in above list with the help of yield keyword
TamilSelvi
Actual Result:
The Application couldn't build. Facing the following Error.
Error:
The body of 'display(List words)' cannot be iterator block because 'void' is not an iterator interface type.
Answer
You are using yield wrong, you need to return an IEnumerable
IEnumerable display(List words) // display method implementation
{
foreach (string word in words)
{
if (word == "TamilSelvi") yield return word;
}
}
Usage
var result = display(names);
foreach (var name in result)
{
Console.WriteLine(name);
}
Additional Resources
Iterator methods and get accessors
The declaration of an iterator must meet the following requirements:
The return type must be IEnumerable, IEnumerable, IEnumerator, or IEnumerator.
The declaration can't have any in ref or out parameters.
No comments:
Post a Comment