Represent an array in C #

I have an array or list from linq. I want to show it as a string in the console! What should I do?

0


a source to share


6 answers


The most general answer I can give you is to loop through each element and use a method ToString()

on each element.



Alternatively, you can serialize Array / List to Xml.

+2


a source


String.Join(delimiter, array);

      

You can think of it as:



Console.WriteLine("{" + String.Join(", ", array) + "}");

      

Of course, I think this only works with strings.

+7


a source


Just iterate over it?

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

      

+1


a source


Typically, you can loop through it if it's a collection or an array. Check keywordforeach

List<Object> list = ...

foreach (Object o in list) {
  Console.WriteLine(o.ToString);
}

      

0


a source


If you want to take a more LINQ approach, you can use the following:

String text = String.Join("," + Environment.NewLine, list.Select(item => item.ToString()).ToArray());
Console.WriteLine(text);

      

The first join parameter determines which characters should be inserted between array elements. Using .Select on a list is to get the string representation of your item in an array.

0


a source


I would like to get more details on what you want to see, but red first, I would try something like:

public string StringFromArray(string[] myArray)
    {
        string arrayString = "";
        foreach (string s in myArray)
        {
            arrayString += s + ", ";
        }
        return arrayString;
    }

      

-1


a source







All Articles