开发者

Print out only odd elements from an IEnumerable?

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

int[] numbers = n开发者_开发技巧ew 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);
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜