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
2010-05-22 00:56:05
+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
2010-05-22 01:04:35
how can I separate between them by space ?
salamonti
2010-05-22 01:18:05
`string.Join(" ", list.ToArray());`
Matt Greer
2010-05-22 01:32:37
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
2010-05-22 01:12:20
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
2010-05-22 01:28:58
@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
2010-05-22 02:09:22