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
Bookmark this link on del.icio.us (saved by 0 users)
Did you like this post?
|
|
|
||
|
|
|
|
|
|
|
subscribe via rss |
|
subscribe via e-mail |
|
|
print this post |
|
follow me on twitter |





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