Saturday, December 1, 2012

Get Even and Odd Number Within a Given Range


In this example we will be using IEnumerable interface in order to loop through the collection of numbers instead of using the commonly used for loop.

Enumerable.Range
Generates a sequence of integral numbers within a specified range.
a simple example would be as follows

// Generate a sequence of integers from 1 to 5  
// and then select their addition.
IEnumerable<int> squares = Enumerable.Range(1, 5).Select(x =>  x + x);
foreach (int num in squares)
{
Console.WriteLine(num);
}

/*
This code produces the following output:

2
4
6
8
10
*/
We can write two methods as below to get even and odd numbers from a giver range

 public static IEnumerable<int> GetEvenNumbers(int FromNumber,int ToNumber)
    {
        int ToRange = 0;
        ToRange = (ToNumber - FromNumber);
        ToRange++;
        IEnumerable<int> arr = Enumerable.Range(FromNumber, ToRange).Where(r => r % 2 ==   0).ToList();

        return arr;
    }


    public static IEnumerable<int> GetOddNumbers(int FromNumber, int ToNumber)
    {
        int ToRange = 0;
        ToRange = (ToNumber - FromNumber);
        IEnumerable<int> arr = Enumerable.Range(FromNumber, ToRange).Where(r => r % 2 != 0).ToList();

        return arr;
    }

No comments:
Write comments
Recommended Posts × +