Generate Odd Numbers within a Range using LINQ

The Enumerable.Range method generates a sequence of integral numbers within a specified range. Here’s how to use it to generate a sequence of odd numbers within a given range say 20 to 40:


static void Main(string[] args)
IEnumerable<int> oddNums =
Enumerable.Range(20, 20).Where(x => x % 2 != 0);

foreach (int n in oddNums)



Sub Main(ByVal args() As String)
Dim oddNums As IEnumerable(Of Integer) = _
Enumerable.Range(20, 20).Where(Function(x) x Mod 2 <> 0)

For Each n As Integer In oddNums
Next n

End Sub

Note: Just remember that the Enumerable.Range accepts two parameters: Start and Count. So if you want to generate numbers from 25 to 50 (inclusive of both), you would say Enumerable.Range(25,26) since the second parameter is the number of sequential integers to generate.


Generate Odd Numbers LINQ

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


Anonymous said...

IEnumerable oddNums =
Enumerable.Range(20, 40).Where(x => x % 2 != 0);

Dinesh Chrysler said...

good one...

Anonymous said...