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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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...