[c#] Concat all strings inside a List<string> using LINQ

Is there any easy LINQ expression to concatenate my entire List<string> collection items to a single string with a delimiter character?

What if the collection is of custom objects instead of string? Imagine I need to concatenate on object.Name.

This question is related to c# linq .net-3.5

The answer is


You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!


List<string> strings = new List<string>() { "ABC", "DEF", "GHI" };
string s = strings.Aggregate((a, b) => a + ',' + b);

Put String.Join into an extension method. Here is the version I use, which is less verbose than Jordaos version.

  • returns empty string "" when list is empty. Aggregate would throw exception instead.
  • probably better performance than Aggregate
  • is easier to read when combined with other LINQ methods than a pure String.Join()

Usage

var myStrings = new List<string>() { "a", "b", "c" };
var joinedStrings = myStrings.Join(",");  // "a,b,c"

Extensionmethods class

public static class ExtensionMethods
{
    public static string Join(this IEnumerable<string> texts, string separator)
    {
        return String.Join(separator, texts);
    }
}

Good question. I've been using

List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
string joinedString = string.Join(", ", myStrings.ToArray());

It's not LINQ, but it works.


I have done this using LINQ:

var oCSP = (from P in db.Products select new { P.ProductName });

string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));

You can use Aggregate, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.

You can use Aggregate function with a seed string.

var seed = string.Empty;
var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carAggregate = cars.Aggregate(seed,
                (partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');

you can use string.Join doesn’t care if you pass it an empty collection.

var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carJoin = string.Join(seperator, cars);


I think that if you define the logic in an extension method the code will be much more readable:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

String.Join(delimiter, list);

is sufficient.


This is for a string array:

string.Join(delimiter, array);

This is for a List<string>:

string.Join(delimiter, list.ToArray());

And this is for a list of custom objects:

string.Join(delimiter, list.Select(i => i.Boo).ToArray());

using System.Linq;

public class Person
{
  string FirstName { get; set; }
  string LastName { get; set; }
}

List<Person> persons = new List<Person>();

string listOfPersons = string.Join(",", persons.Select(p => p.FirstName));

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to .net-3.5

Get first element from a dictionary redistributable offline .NET Framework 3.5 installer for Windows 8 How to read an entire file to a string using C#? HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.) Change the Textbox height? How to get current date in 'YYYY-MM-DD' format in ASP.NET? C# Numeric Only TextBox Control Will the IE9 WebBrowser Control Support all of IE9's features, including SVG? Use LINQ to get items in one List<>, that are not in another List<> Get Absolute URL from Relative path (refactored method)