tags:

views:

211

answers:

4

how to concatenate all content of list in on one string in c#?

A: 

Something like this:

    List<String> myStrings = new List<string>() { "string1", "string2", "string3" };
    StringBuilder concatenatedString = new StringBuilder();
    foreach (String myString in myStrings)
    {
        concatenatedString.Append(myString);
    }
    Console.WriteLine(concatenatedString.ToString());
Canoehead
+5  A: 

Searching for this:

List<string> list = new List<string>(); // { "This ", "is ", "your ", "string!"};
        list.Add("This ");
        list.Add("is ");
        list.Add("your ");
        list.Add("string!");

        string concat = String.Join(String.Empty, list.ToArray());
Secko
how can I separate between them by space ?
salamonti
`string.Join(" ", list.ToArray());`
Matt Greer
A: 
public static string ToString(this IEnumerable<T> source, string delimiter)
{
    string d = String.Empty;
    var result = new StringBuilder();
    foreach(string item in source)
    {
        result.Append(d).Append(item.ToString());
        d = delimiter;
    }
    return result.ToString();
}
Joel Coehoorn
A: 

Here is a version that separates elements using two spaces implemented using LINQ:

var s = list.Aggregate(new StringBuilder(), (sb, current) => 
  sb.AppendFormat("{0}  ", current)).ToString();

The Aggregate method passes the StringBuilder (as sb) with the current element of the list (as current) to the lambda expression which can do anything it needs - for example append the current string from the list to the StringBuilder using some formatting specified in the lambda expression body.

Tomas Petricek
No need to reinvent the wheel. `string.Join` does it all.
Matt Greer
@Matt: You're right - it allows you to specify a separator (I forgot about that), but in some cases, you may still need more powerful solution.
Tomas Petricek
Yeah, true. And the more LINQ gets exposed the better.
Matt Greer