48

Trying to determine if my list of integer is made of odd or even numbers, my desired output is a list of true an/or false. Can I perform the following operation on the list lst or do I need to create a loop? A is the output.

    List <int> lst = new List <int>();
    A = IsOdd(lst);
Arthur Mamou-Mani
  • 2,303
  • 10
  • 43
  • 69

5 Answers5

69

You could try using Linq to project the list:

var output = lst.Select(x => x % 2 == 0).ToList();

This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • Works very well, thank you! already reading about linq: http://msdn.microsoft.com/en-us/library/vstudio/bb397933.aspx, can you define what linq does over usual C# ? – Arthur Mamou-Mani Sep 16 '13 at 00:05
  • 3
    @ArthurMamou-Mani -- in short, it lets you "abstract" the idea of looping. If you were to avoid using LINQ, you would need to make a new list, iterate through the old one, add to the new one, etc... It just gets tedious over time, having to constantly rethink and re-engineer the same basic operations -- mapping, filtering, etc. Using LINQ lets you write what you want to happen, and chain a bunch of common operations together, instead of having to reimplement a long and complex sequence of nested for-loops each time. It's a huge time saver, and generally tends to result in more efficient code. – Michael0x2a Sep 16 '13 at 00:09
  • would like add to @Michael0x2a's sublime comment that LINQ is waaaaaaay more understandable than wading through multiple nested loops. – BenKoshy Dec 15 '16 at 11:50
63

Just use the modulus

loop through the list and run the following on each item

if(num % 2 == 0)
{
  //is even
}
else
{
  //is odd
}

Alternatively if you want to know if all are even you can do something like this:

bool allAreEven = lst.All(x => x % 2 == 0);
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 4
    You can bost your `allAreEven` performannce with `!lst.Any(x => x % 2 != 0);` Imagine a list with millions of items and the first is odd, theres no need to compute the rest. – Jürgen Steinblock Sep 23 '15 at 07:45
  • @JürgenSteinblock `All` will also short-circuit in the same manner you have described. Proof: https://stackoverflow.com/a/9027666/8306962 – Issung Jul 19 '21 at 01:57
24

There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:

if (x % 2 == 0)
               //even number
        else
               //odd number

Here are a few other methods (from the website) :

//bitwise operation
if ((x & 1) == 0)
       //even number
else
      //odd number

//bit shifting
if (((x >> 1) << 1) == x)
       //even number
else
       //odd number

//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
       //even number
else
       //odd number
Free Coder 24
  • 933
  • 9
  • 12
2
        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }
Newby25
  • 21
  • 1
-1

--simple codes--

        #region odd / even numbers  order by desc

        //declaration of integer
        int TotalCount = 50;
        int loop;

        Console.WriteLine("\n---------Odd Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 == 0)
            {
                Console.WriteLine("Even numbers : #{0}", loop);
            }
        }

        Console.WriteLine("\n---------Even Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 != 0)
            {
                Console.WriteLine("odd numbers : #{0}", loop);
            }
        }

        Console.ReadLine();

        #endregion
Prabal Kajla
  • 125
  • 12