Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out only odd elements from an IEnumerable?

Tags:

c#

ienumerable

I am having problems with an array where I for example want to printout the odd numbers in the list.

int[] numbers = new int[]{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
Console.WriteLine(numbers.Where(n => n % 2 == 1).ToArray());

The ToString method does not seem to work? I do not want to loop through the elements. What can I do?

like image 877
James Ford Avatar asked Feb 22 '11 15:02

James Ford


3 Answers

You need to call String.Join to create a string with the contents of the sequence.

For example:

Console.WriteLine(String.Join(", ", numbers.Where(n => n % 2 == 1));

This uses the new overload which takes an IEnumerable<T>.
In .Net 3.5, you'll need to use the older version, which only takes a string[]:

Console.WriteLine(String.Join(
    ", ", 
    numbers.Where(n => n % 2 == 1)
           .Select(n => n.ToString())
           .ToArray()
    )
);
like image 143
SLaks Avatar answered Oct 20 '22 10:10

SLaks


In addition to the other answers which point out that you can't just print out an array, I note that this doesn't print out all the odd numbers in the list because your test for oddness is incorrect. Do you see why?

Hint: try testing it with negative numbers. Did you get the expected result? Why not?

like image 42
Eric Lippert Avatar answered Oct 20 '22 08:10

Eric Lippert


You can use ForEach():

 numbers.ToList().ForEach(

    x=> 
  {if(x % 2 == 1)
      Console.WriteLine(x);
  });
like image 40
Aliostad Avatar answered Oct 20 '22 08:10

Aliostad