LINQ Cookbook, Recipe 3: Find all the prime numbers in a given range (Jonathan Aneja)


          Visual Studio 2008 (Beta2 or Higher)


Categories: LINQ-To-Objects




          Open Visual Studio 2008, and Click ‘File/New Project’. Find and double-click the ‘Console Application’ Icon

         Add the following code:



Module Module1


    Sub Main()

        Dim primes = GetPrimesInRange(30, 50)


        For Each n In primes




    End Sub


    Function GetPrimesInRange(ByVal low, ByVal high) As IEnumerable(Of Integer)

        Dim range = Enumerable.Range(1, high)

        Return From num In range _

               From num2 In range _

               Where num Mod num2 = 0 _

               Group By num Into Count() _

               Where Count = 2 And num > low _

               Select num

    End Function


End Module

          The grouping is used to select only those numbers that have exactly two factors (i.e. they’re prime)