仅打印I​​Enumerable中的奇数元素? [英] Print out only odd elements from an IEnumerable?

查看:66
本文介绍了仅打印I​​Enumerable中的奇数元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个数组问题,例如想打印列表中的奇数.

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

ToString方法似乎不起作用?我不想遍历所有元素.我该怎么办?

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

推荐答案

您需要调用 String.Join 来创建包含序列内容的字符串.

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

例如:

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

这使用了新的重载,该重载需要 IEnumerable< T> .
在.Net 3.5中,您需要使用较旧的版本,该版本只需要 string [] :

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

这篇关于仅打印I​​Enumerable中的奇数元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆