Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate all list content in one string in C#

Tags:

c#

list

People also ask

How do I concatenate a list of items in a string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do I concatenate a char to a string in C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

How do you combine strings in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Does C have concatenation?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.


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 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.


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();
}

Here is a simple solution with StringBuilder:

        var sb = new StringBuilder();
        strings.ForEach(s => sb.Append(s));
        var combinedList = sb.ToString();

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());