C # Load integers and display odd / even

Hello, I wonder if there is an easier way to display odd / even numbers. I know I can do a for loop and load a list. Then I can write another loop to scroll through the list and check if the value is odd / even:

for(i=0; i<100; i++) if(myList[i]%2==0) //even //do something else //odd do something 

But is there any way to shorten this just so that I can easily get a list of odd or even numbers. Not homework is just interesting.

+7
c #
source share
7 answers

Could you use some 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 from 1-100, and then I just grab all the odds / evens and then print them. All this can be reduced 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 are of the implicit type var. The compiler can determine its type so that these two lines are equivalent:

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

Then, to find the coefficients / evens directly to the list type:

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

And for printing, this is indicated in my source code.

+11
source share

LINQ method ... Odd and even numbers from 1 to 100.

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

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

 var even = myList.Where(i => i%2==0); foreach(var number in even) // do something 
+3
source share
 var t = Enumerable.Range(1, 100).ToList(); var oddNumbers = t.Where(n => (n & 1) != 0).ToList(); var evenNumbers = t.Where(n => (n & 1) == 0).ToList(); 
+3
source share

I do not think you need to create the first loop. You could simply:

 for (i=1; i < 101; i++) { if (i % 2 != 0) { //do something } } 

Or even:

 for (i=1, i < 101, i+=2) { //do something } 
+1
source share

Fill out the list according to these formulas

 Odds[0->N] = 2*i+1 Evens[0->N] = 2*i 
0
source share

If you need only half the numbers, just generate half the numbers (..; ..; i = i + 2)

If you need all the numbers, but want to avoid an extra loop, you can mark them or process them during the initial loop.

Or, at creation time, make up to three lists / arrays - one for all numbers, another for coefficients, and a third for evens.

Is there a specific application?

0
source share

All Articles