C# 有没有办法写出完整的IEnumerable<;T>;在一个控制台内。写入(行)?
我有以下代码C# 有没有办法写出完整的IEnumerable<;T>;在一个控制台内。写入(行)?,c#,ienumerable,console.writeline,C#,Ienumerable,Console.writeline,我有以下代码 IEnumerable<int> numbers = Enumerable.Range(1, 5) .Reverse(); Func<int, string> outputFormat = x => x + "..."; IEnumerable<string> countdown = numbers.Select(outputFormat); foreach (string
IEnumerable<int> numbers =
Enumerable.Range(1, 5)
.Reverse();
Func<int, string> outputFormat = x => x + "...";
IEnumerable<string> countdown = numbers.Select(outputFormat);
foreach (string s in countdown)
{
Console.WriteLine(s);
}
没有实际编写自定义方法(例如,以某种方式使用LINQ或委托)您可以使用以下代码:
Console.WriteLine(string.Join(Environment.NewLine, countdown));
请注意,在旧版本的.NET中,接受IEnumerable
的string.Join
没有重载,只有string[]
,在这种情况下,您需要类似以下内容:
Console.WriteLine(string.Join(Environment.NewLine, countdown.ToArray()));
为完整起见,如果集合不包含string
元素,则可以执行以下操作:
Console.WriteLine(string.Join(Environment.NewLine, countdown.Select(v => v.ToString()).ToArray()));
您可以使用以下代码:
Console.WriteLine(string.Join(Environment.NewLine, countdown));
请注意,在旧版本的.NET中,接受IEnumerable
的string.Join
没有重载,只有string[]
,在这种情况下,您需要类似以下内容:
Console.WriteLine(string.Join(Environment.NewLine, countdown.ToArray()));
为完整起见,如果集合不包含string
元素,则可以执行以下操作:
Console.WriteLine(string.Join(Environment.NewLine, countdown.Select(v => v.ToString()).ToArray()));
这应该可以做到:
Console.WriteLine(string.Join(Environment.NewLine, countdown));
这应该可以做到:
Console.WriteLine(string.Join(Environment.NewLine, countdown));
您可以使用扩展方法:
public static void WriteLines<T> (this IEnumerable<T> @this)
{
foreach (T item in @this)
Console.WriteLine(item);
}
优点:
您可以使用扩展方法:
public static void WriteLines<T> (this IEnumerable<T> @this)
{
foreach (T item in @this)
Console.WriteLine(item);
}
优点:
将
Console.WriteLine(string.Join(“,”,倒计时))代码>玩这个把戏?可选倒计时.ToList().ForEach(Console.WriteLine)代码>将Console.WriteLine(string.Join(“,”,倒计时))代码>玩这个把戏?可选倒计时.ToList().ForEach(Console.WriteLine)代码>不是我想要的,但如果内存有问题,这绝对是一种替代方法+1这并不是我想要的,但如果内存有问题,这绝对是一种替代方法+1.