13

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?

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
James Ford
  • 949
  • 4
  • 12
  • 25
  • Related: https://stackoverflow.com/questions/7481964/how-to-convert-ienumerablestring-to-one-comma-separated-string – StayOnTarget Mar 19 '21 at 13:53

3 Answers3

22

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()
    )
);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
6

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?

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
5

You can use ForEach():

 numbers.ToList().ForEach(

    x=> 
  {if(x % 2 == 1)
      Console.WriteLine(x);
  });
Aliostad
  • 80,612
  • 21
  • 160
  • 208