convert (list)

C

csharpula csharp

Hello,
I am looking for a way to convert list<string> to string (one string
conainig all list members).
How can I do it in an elegant way ? (I mean without foreach and
appendind strings)
Thank u!
 
L

Lasse Vågsæther Karlsen

csharpula said:
Hello,
I am looking for a way to convert list<string> to string (one string
conainig all list members).
How can I do it in an elegant way ? (I mean without foreach and
appendind strings)
Thank u!

String s = String.Join(Environment.NewLine, list.ToArray());
 
M

Marc Gravell

Note that if you have an array (not a list), then string.Join() is
useful - but it isn't realy worth doing .ToArray() just to use
string.Join().

With a List<string>, StringBuilder is the way to go; this is perhaps
something that befits an "extension" method in C# 3 - the following
works in VS2008, for example:

// usage
static void Main()
{
var items = new List<string> {"abc", "def", "ghi"};
string csv = items.Concat(",");
}

// (in some utility library somewhere)
public static string Concat(this IEnumerable<string> items,
string separator)
{
if (items == null) throw new
ArgumentNullException("items");
StringBuilder sb = new StringBuilder();
foreach (string item in items)
{
if (sb.Length > 0) sb.Append(separator);
sb.Append(item);
}
return sb.ToString();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top