C# Print list of string array

后端 未结 5 2057
说谎
说谎 2021-01-02 01:02

I\'m very new to c# and have a question, how do I print list of string arrays? I can do it from string[] using Console.WriteLine, but if I do that for list with forEach it j

相关标签:
5条回答
  • 2021-01-02 01:45
    string[] arr = new string[2]{"foo","zoo"}; // sample Initialize.
    
    // Loop over strings.
    foreach (string s in arr)
    {
        Console.WriteLine(s);
    }
    

    The console output:

    foo
    zoo
    
    0 讨论(0)
  • 2021-01-02 01:48

    In a string array to get the index you do it:

    string[] names = new string[3] { "Matt", "Joanne", "Robert" };
    
    int counter = 0;
    foreach(var name in names.ToList())
    {
     Console.WriteLine(counter.ToString() + ":-" + name);
     counter++;
    }
    
    0 讨论(0)
  • 2021-01-02 01:58

    This works for me:

    var strArray = new string[] {"abc","def","asd" };
    strArray.ToList().ForEach(Console.WriteLine);
    
    0 讨论(0)
  • 2021-01-02 02:04

    Simplest way to achieve this is: using String.Join

    string[] arr = new string[] { "one", "two", "three", "four" };
    Console.WriteLine(String.Join("\n", arr)); 
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-02 02:04

    So you have list of string arrays, like this:

     List<string[]> data = new List<string[]>() {
       new string[] {"A", "B", "C"},
       new string[] {"1", "2"},
       new string[] {"x", "yyyy", "zzz", "final"},
     };
    

    To print on, say, the Console, you can implement nested loops:

     foreach (var array in data) {
       Console.WriteLine();
    
       foreach (var item in array) {
         Console.Write(" ");
         Console.Write(item); 
       }
     }
    

    Or Join the items into the single string and then print it:

     using System.Linq;
     ...
    
     string report = string.Join(Environment.NewLine, data
       .Select(array => string.Join(" ", array)));
    
     Console.Write(report);
    

    Or combine both methods:

     foreach (var array in data) 
       Console.WriteLine(string.Join(" ", array));
    
    0 讨论(0)
提交回复
热议问题