145

How do I make this output to a string?

List<string> Client = new List<string>();
foreach (string listitem in lbClients.SelectedItems)
{
    Client.Add(listitem);
}
3
  • 3
    What type of string? Delimiter separated? Commented Nov 17, 2012 at 0:43
  • What do you want the resulting string to look like? Commented Nov 17, 2012 at 0:46
  • What version of the .NET framework are you using? The suggested String.Join() overload was added in .NET 4, before which the method only took an Array. Commented Nov 17, 2012 at 0:50

4 Answers 4

308

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

Sign up to request clarification or add additional context in comments.

Comments

17

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

http://msdn.microsoft.com/en-us/library/dd992421.aspx

In your example, you'd use

String.Join("", Client);

Comments

12

You can write like this:

string[] arr = { "Miami", "Berlin", "Hamburg"};
string s = string.Join(" ", arr);

Comments

10

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

2 Comments

Your answer is functionally no different to the others. string.Join<T>(String, IEnumerable<T>) already calls ToString() on the items, and there is a string.Join(String, IEnumerable<String>) method that doesn't need the ToArray().
Selecting the list element and converting to string avoids the ambiguity in different data types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.