Using Yield Statement example

Posted by Ravyii under C# category on | Points: 40 | Views : 1099
You might noticed yield statment, here i like to show an example of removing duplicates from a collection using this statment.
Consider we have a collection

List<string> stringCollection = new List<string> { "India", "Nepal", "Srilanka", "Pakisthan", "Nepal", "China"  };

Now if we want to remove the duplicate in this collection so i will declare another temporary collection to filter out the duplicates

List<string> NewCollection = new List<string>();

Now i will create a function which will give items not available from the source collection

private IEnumerable<string> RemoveDuplicates(List<string> sourceCollection, string str)
if (!sourceCollection.Contains(str))
yield return str;
yield break;

Note yield statment works only with IEnumerable.

Now the main method which will iterate through the source collection and populate the temporary collection

foreach (string x in stringCollection)
IEnumerable<string> str = RemoveDuplicates(NewCollection, x);
Finally NewCollection will have distinct of items from source collection.

Comments or Responses

Login to post response