C# IEnumerable print out

这一生的挚爱 提交于 2020-01-02 00:55:23

问题


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?


回答1:


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()
    )
);



回答2:


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?




回答3:


You can use ForEach():

 numbers.ToList().ForEach(

    x=> 
  {if(x % 2 == 1)
      Console.WriteLine(x);
  });


来源:https://stackoverflow.com/questions/5079867/c-sharp-ienumerable-print-out

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!