UNKNOWN //************************************** // Name: Using Yield Keyword // Description:Four examples of using yield Keyword in VB .Net 2012 // By: Salem Al Shekaili // // // Inputs:None // // Returns:None // //Assumes:None // //Side Effects:None //This code is copyrighted and has limited warranties. //Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.9098/lngWId.10/qx/vb/scripts/ShowCode.htm //for details. //************************************** Module Module1 Sub Main() // 'example 1 ShowingFiles() // 'example 2 Oddnumber() // 'example 3 prime() // 'example 4 Some_number() Console.ReadKey() End Sub Private Sub prime() For Each numbers As Long In PrimesNumber(50) Console.WriteLine(numbers.ToString() + Environment.NewLine) Next End Sub // 'example 4 Private Sub Some_number() For Each number As Integer In SomeNumbers() Console.Write(number & " ") Next End Sub Private Sub ShowingFiles() For Each file_Name In FileToProcessIterator() // ' Do something; process file Console.WriteLine(file_Name) Next End Sub Private Iterator Function FileToProcessIterator() As IEnumerable(Of String) For Each file_Name In System.IO.Directory.EnumerateFiles("c:\", "*.*") Yield file_Name Next End Function Public Iterator Function ReturnTenThings10() As IEnumerable(Of String) Dim Ret As New List(Of String)() For I As Integer = 0 To 9 Threading.Thread.Sleep(1000) Yield (I + 1).ToString() Next End Function Private Iterator Function SomeNumbers() As System.Collections.IEnumerable Yield 3 Yield 5 Yield 8 End Function Private Iterator Function CityNames() As System.Collections.IEnumerable Dim str As String() = {"Abu Dhabi", "Londan", "Dubai", "Sharjah", "Ras Al kymah"} For i As Integer = 0 To str.Length - 2 Yield str(i) & " City " Next End Function Private Sub Oddnumber() For Each strCity As String In CityNames() System.Console.Write(strCity & " ") Next End Sub 'This below function shows how to find a // number's prime factors in Visual Basic . // NET. Private Iterator Function PrimesNumber(num As Integer) As IEnumerable(Of Long) Dim isPrime As Boolean = False // ' Take out the 2s. For i As Integer = 2 To num isPrime = False If i = 2 Then Yield i Continue For End If ' We don't care about even numbers (exce // pt 2) If i Mod 2 = 0 Then Continue For End If isPrime = True For j As Integer = 2 To CLng(Math.Sqrt(i)) ' Check if current value is divisible by // something // ' other than 1 and itself If i Mod j = 0 Then isPrime = False Exit For End If Next If isPrime Then Yield i Next End Function End Module