jQuery and ASP.NET

March 20, 2010

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:

C#

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

foreach (int n in oddNums)
{
Console.WriteLine(n);
}
Console.ReadLine();

}

VB.NET

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
Console.WriteLine(n)
Next n
Console.ReadLine()

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.

OUTPUT

Generate Odd Numbers LINQ



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Generate Odd Numbers within a Range using LINQ"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions