C# Load integers and display odd / even

The LINQ way... Odd and Even numbers between 1 and 100.

var even = Enumerable.Range(1,100).Where(i => i % 2 == 0);
var odd = Enumerable.Range(1,100).Where(i => i % 2 != 0);

Could you use some sort of lambdas:

//load a list, t, with 100 integers
List<int> t = Enumerable.Range(1, 100).ToList();

//find odd numbers
var oddNumbers = t.Where(num => num%2 != 0);

//find even numbers
var evenNumbers = t.Where(num => num%2 == 0);

//print odd numbers
foreach (int i in oddNumbers)
    Console.WriteLine(i);

//print even numbers
    foreach(int i in evenNumbers)
        Console.WriteLine(i);

The Enumerable just loads the list with 1-100, and then I simply snatch all odds / evens and then print them. This all can be shortened to:

var e = Enumerable.Range(1, 100).Where(num => num%2==0); //for even numbers
var o = Enumerable.Range(1, 100).Where(num => num%2!=0); //for odd numbers

e,o have an implicit type var. The compiler can determine its type so these two lines are equivalent to:

List<int> eo = Enumerable.Range(1, 100).ToList(); //must tell it its a list

Then to find the odds / evens directly to a list type:

List<int> o = eo.Where(num => num%2!=0).ToList();
List<int> e = eo.Where(num => num%2==0).ToList();

And to print it is listed in my initial code.


You can use LINQ to pull out just the odd or even, and then process:

var even = myList.Where(i => i%2==0);
foreach(var number in even)
     // do something

Tags:

C#