【问题标题】:Is there a way to write whole IEnumerable<T> within one Console.Write(line)?有没有办法在一个 Console.Write(line) 中编写整个 IEnumerable<T>?
【发布时间】:2014-08-08 12:34:29
【问题描述】:

我有以下代码

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

有没有办法从代码中“消除”foreach 循环,比如

Console.Write(countdown.EnumerateOverItems())

没有实际编写自定义方法(例如,以某种方式使用 LINQ 或委托)?

【问题讨论】:

  • Console.WriteLine(string.Join(", ", countdown)); 能解决问题吗?
  • 可选countdown.ToList().ForEach(Console.WriteLine);

标签: c# ienumerable console.writeline


【解决方案1】:

这应该可以解决问题:

Console.WriteLine(string.Join(Environment.NewLine, countdown));

【讨论】:

    【解决方案2】:

    您可以使用以下代码:

    Console.WriteLine(string.Join(Environment.NewLine, countdown));
    

    请注意,在旧版本的 .NET 中,string.Join 没有重载,它采用 IEnumerable&lt;T&gt;,只有 string[],在这种情况下,您需要类似:

    Console.WriteLine(string.Join(Environment.NewLine, countdown.ToArray()));
    

    为了完整起见,如果集合不包含string 元素,您可以这样做:

    Console.WriteLine(string.Join(Environment.NewLine, countdown.Select(v => v.ToString()).ToArray()));
    

    【讨论】:

      【解决方案3】:

      您可以使用扩展方法:

      public static void WriteLines<T> (this IEnumerable<T> @this)
      {
          foreach (T item in @this)
              Console.WriteLine(item);
      }
      

      用法:

      new[]{ "a", "b" }.WriteLines();
      

      优点:

      1. 字符串分配将减少。
      2. 使用代码更少。

      缺点:

      1. 自定义方法,模式代码。

      【讨论】:

      • 不是我真正想要的,但如果内存成为问题,这绝对是一种替代方法。 +1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2021-09-10
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      相关资源
      最近更新 更多