Concatenate all list content in one string in C#
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(" ", list.ToArray());
You can use the Aggregate function to concatenate all items of a list.
The following is the example to concatenate all the items of a list with comma ","
string s = list.Aggregate((i, j) => i + "," + j).ToString();
If you need to transform your list elements while joining, you can use LINQ:
string.Join(", ", mylist.Select(z => MyMethod(z)));
Example:
IEnumerable<string> mylist = new List<string>() {"my", "cool", "list"};
string joined = string.Join(", ", mylist.Select(z => MyMethod(z)));
public string MyMethod(string arg)
{
return arg.ToUpper();
}
If you have some properties within your objects and want to do some more formatting there, then using LINQ,
var output = string.Join(" ", list.Select(t => t.Prop1 + " " + t.Prop2));
This will put a space in between each of the properties of your objects and a space in between each object as well.