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?
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()
)
);
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?
You can use ForEach()
:
numbers.ToList().ForEach(
x=>
{if(x % 2 == 1)
Console.WriteLine(x);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With