How to display list items on console window in C#

后端 未结 7 1308
执笔经年
执笔经年 2020-11-29 00:19

I have a List which contains all databases names. I have to dispaly the items contained in that list in the Console (using Console.WriteLine()). Ho

7条回答
  •  执笔经年
    2020-11-29 00:46

    While the answers with List.ForEach are very good.

    I found String.Join(string separator, IEnumerable values) method more useful.

    Example :

    List numbersStrLst = new List
                { "One", "Two", "Three","Four","Five"};
    
    Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
    
    int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
    Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
    

    Remarks :

    If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.

    Join(String, IEnumerable) is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.

    This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])

    Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

提交回复
热议问题