【问题标题】:printing all contents of array in C#在 C# 中打印数组的所有内容
【发布时间】:2013-04-28 16:51:31
【问题描述】:

在调用一些改变数组的方法后,我试图打印出数组的内容,在我使用的 Java 中:

System.out.print(Arrays.toString(alg.id));

如何在 C# 中做到这一点?

【问题讨论】:

  • a) 使用 F# (printfn "%A\n" [| 1, 2, 3 |]) 或 b) 使用 Common Lisp ((let ((arr #(1 2 3))) (print arr)))。在使用其他语言多年后用 C# 编写了一些 SO 答案后,我不敢相信结构和数组的通用输出仍然不是 C# 的一部分。

标签: c# .net arrays linq


【解决方案1】:

你可以试试这个:

foreach(var item in yourArray)
{
    Console.WriteLine(item.ToString());
}

你也可以试试这样的:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

编辑:在一行中获得输出[根据您的评论]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

EDIT(2019):正如其他答案中提到的,最好使用Array.ForEach<T> 方法,无需执行ToList 步骤。

Array.ForEach(yourArray, Console.WriteLine);

【讨论】:

  • 请注意,.ToString 不是必需的,因为 WriteLine 有各种重载,包括采用 Object 的后备。
  • 我使用了 alg.Id.ToList().ForEach(Console.WriteLine),效果很好,谢谢。是否可以实际打印如下: [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]
  • ForEach 方法上使用:expected.ToList().ForEach(Console.WriteLine); 您可以使用方法引用而不是 lambda,这将创建一个新的无用匿名方法。
  • 使用ToList 创建一个列表只是为了使用ForEach 方法是一种可怕的做法恕我直言。
  • 反正我的答案没必要复制粘贴到你的
【解决方案2】:

有很多方法可以做到,其他答案都不错,这里有一个替代方案:

Console.WriteLine(string.Join("\n", myArrayOfObjects));

【讨论】:

  • 我喜欢这个因为很适合我写日志:例如myArrayObjects is _validExtensions: Write2Log("Start blabla with the exenstions: " + string.Join("-", _validImgExtensions) + " etc");
  • 我也喜欢这个,因为它非常适合日志记录;如果数组元素是您的对象之一,您可以覆盖 ToString() 并在那里处理格式。 var a = new [] { "Admin", "Peon" };_log.LogDebug($"Supplied roles are '{string.Join(", ", a)}'.");
【解决方案3】:

最简单的一个,例如如果你有一个这样声明的字符串数组 string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

【讨论】:

    【解决方案4】:

    我决定测试这里发布的不同方法的速度:

    这是我使用的四种方法。

    static void Print1(string[] toPrint)
    {
        foreach(string s in toPrint)
        {
            Console.Write(s);
        }
    }
    
    static void Print2(string[] toPrint)
    {
        toPrint.ToList().ForEach(Console.Write);
    }
    
    static void Print3(string[] toPrint)
    {
        Console.WriteLine(string.Join("", toPrint));
    }
    
    static void Print4(string[] toPrint)
    {
        Array.ForEach(toPrint, Console.Write);
    }
    

    结果如下:

     Strings per trial: 10000
     Number of Trials: 100
     Total Time Taken to complete: 00:01:20.5004836
     Print1 Average: 484.37ms
     Print2 Average: 246.29ms
     Print3 Average: 70.57ms
     Print4 Average: 233.81ms
    

    所以 Print3 是最快的,因为它只有一次调用 Console.WriteLine,这似乎是打印出数组速度的主要瓶颈。 Print4 比 Print2 稍快,而 Print1 是最慢的。

    我认为 Print4 可能是我测试的 4 个中最通用的,尽管 Print3 更快。

    如果我犯了任何错误,请随时让我知道/自行修复它们!

    编辑:我在下面添加生成的 IL

    g__Print10_0://Print1
    IL_0000:  ldarg.0     
    IL_0001:  stloc.0     
    IL_0002:  ldc.i4.0    
    IL_0003:  stloc.1     
    IL_0004:  br.s        IL_0012
    IL_0006:  ldloc.0     
    IL_0007:  ldloc.1     
    IL_0008:  ldelem.ref  
    IL_0009:  call        System.Console.Write
    IL_000E:  ldloc.1     
    IL_000F:  ldc.i4.1    
    IL_0010:  add         
    IL_0011:  stloc.1     
    IL_0012:  ldloc.1     
    IL_0013:  ldloc.0     
    IL_0014:  ldlen       
    IL_0015:  conv.i4     
    IL_0016:  blt.s       IL_0006
    IL_0018:  ret         
    
    g__Print20_1://Print2
    IL_0000:  ldarg.0     
    IL_0001:  call        System.Linq.Enumerable.ToList<String>
    IL_0006:  ldnull      
    IL_0007:  ldftn       System.Console.Write
    IL_000D:  newobj      System.Action<System.String>..ctor
    IL_0012:  callvirt    System.Collections.Generic.List<System.String>.ForEach
    IL_0017:  ret         
    
    g__Print30_2://Print3
    IL_0000:  ldstr       ""
    IL_0005:  ldarg.0     
    IL_0006:  call        System.String.Join
    IL_000B:  call        System.Console.WriteLine
    IL_0010:  ret         
    
    g__Print40_3://Print4
    IL_0000:  ldarg.0     
    IL_0001:  ldnull      
    IL_0002:  ldftn       System.Console.Write
    IL_0008:  newobj      System.Action<System.String>..ctor
    IL_000D:  call        System.Array.ForEach<String>
    IL_0012:  ret   
    

    【讨论】:

      【解决方案5】:

      Array 类的Array.ForEach&lt;T&gt; Method (T[], Action&lt;T&gt;) 方法的另一种方法

      Array.ForEach(myArray, Console.WriteLine);
      

      array.ToList().ForEach(Console.WriteLine) 相比,它只需要一次迭代,array.ToList().ForEach(Console.WriteLine) 需要两次迭代并在内部为List 创建第二个数组(双倍迭代运行时间和双倍内存消耗)

      【讨论】:

      • 我最喜欢你的方法,根据我的测试,它是第二快的,但它比最快的方法更通用(在我看来)。
      【解决方案6】:

      在 C# 中,您可以循环打印每个元素的数组。请注意,System.Object 定义了一个 ToString() 方法。从 System.Object() 派生的任何给定类型都可以覆盖它。

      返回一个代表当前对象的字符串。

      http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

      默认情况下,将打印对象的完整类型名称,尽管许多内置类型会覆盖该默认值以打印更有意义的结果。您可以在自己的对象中覆盖 ToString() 以提供有意义的输出。

      foreach (var item in myArray)
      {
          Console.WriteLine(item.ToString()); // Assumes a console application
      }
      

      如果你有自己的类 Foo,你可以像这样覆盖 ToString():

      public class Foo
      {
          public override string ToString()
          {
              return "This is a formatted specific for the class Foo.";
          }
      }
      

      【讨论】:

        【解决方案7】:

        C# 6.0开始,在引入$ - 字符串插值的时候,多了一种方式:

        var array = new[] { "A", "B", "C" };
        Console.WriteLine($"{string.Join(", ", array)}");
        
        //output
        A, B, C
        

        可以使用System.Linq 归档串联,将string[] 转换为char[] 并打印为string

        var array = new[] { "A", "B", "C" };
        Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");
        
        //output
        ABC
        

        【讨论】:

          【解决方案8】:

          如果你想变得可爱,你可以编写一个扩展方法,将IEnumerable&lt;object&gt; 序列写入控制台。这适用于任何类型的枚举,因为IEnumerable&lt;T&gt; 在 T 上是协变的:

          using System;
          using System.Collections.Generic;
          
          namespace Demo
          {
              internal static class Program
              {
                  private static void Main(string[] args)
                  {
                      string[] array  = new []{"One", "Two", "Three", "Four"};
                      array.Print();
          
                      Console.WriteLine();
          
                      object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};
                      objArray.Print();
                  }
              }
          
              public static class MyEnumerableExt
              {
                  public static void Print(this IEnumerable<object> @this)
                  {
                      foreach (var obj in @this)
                          Console.WriteLine(obj);
                  }
              }
          }
          

          (我认为您不会在测试代码中使用它。)

          【讨论】:

          • 花了我一段时间才完全理解,但这非常方便,我习惯了 Python 并放入 print 语句来帮助调试,所以这对我有好处。谢谢
          【解决方案9】:

          我赞成 Matthew Watson 的扩展方法答案,但如果您从 Python 迁移/访问,您可能会发现这样的方法很有用:

          class Utils
          {
              static void dump<T>(IEnumerable<T> list, string glue="\n")
              {
                  Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
              }
          }
          

          -> 这将使用提供的分隔符打印任何集合。它非常有限(嵌套集合?)。

          对于脚本(即仅包含 Program.cs 的 C# 控制台应用程序,大多数事情发生在 Program.Main) - 这可能很好。

          【讨论】:

            【解决方案10】:

            这是使用数组打印字符串的最简单方法!!!

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            
            namespace arraypracticeforstring
            {
                class Program
                {
                    static void Main(string[] args)
                    {
                        string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };
            
                        foreach (string item in arr)
                        {
                            Console.WriteLine(item.ToString());
                        }
                        Console.ReadLine();
                    }
                }
            }
            

            【讨论】:

              【解决方案11】:

              如果是字符串数组,可以使用Aggregate

              var array = new string[] { "A", "B", "C", "D"};
              Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D
              

              这样你可以通过改变参数的顺序来反转顺序

              Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A
              

              【讨论】:

                【解决方案12】:

                你可以使用for循环

                    int[] random_numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14}
                    int array_length = random_numbers.Length;
                    for (int i = 0; i < array_length; i++){
                        if(i == array_length - 1){
                              Console.Write($"{random_numbers[i]}\n");
                        } else{
                              Console.Write($"{random_numbers[i]}, ");
                         }
                     }
                

                【讨论】:

                  【解决方案13】:

                  如果您不想使用数组功能。

                  public class GArray
                  {
                      int[] mainArray;
                      int index;
                      int i = 0;
                  
                      public GArray()
                      {
                          index = 0;
                          mainArray = new int[4];
                      }
                      public void add(int addValue)
                      {
                  
                          if (index == mainArray.Length)
                          {
                              int newSize = index * 2;
                              int[] temp = new int[newSize];
                              for (int i = 0; i < mainArray.Length; i++)
                              {
                                  temp[i] = mainArray[i];
                              }
                              mainArray = temp;
                          }
                          mainArray[index] = addValue;
                          index++;
                  
                      }
                      public void print()
                      {
                          for (int i = 0; i < index; i++)
                          {
                              Console.WriteLine(mainArray[i]);
                          }
                      }
                   }
                   class Program
                  {
                      static void Main(string[] args)
                      {
                          GArray myArray = new GArray();
                          myArray.add(1);
                          myArray.add(2);
                          myArray.add(3);
                          myArray.add(4);
                          myArray.add(5);
                          myArray.add(6);
                          myArray.print();
                          Console.ReadKey();
                      }
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2015-12-08
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-04-02
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多