How to Create a Comma Separated List in C#

  1. Using the String.Join() Method to Create a Comma Separated List in C#
  2. Using the LINQ Aggregate Method to Create a Comma Separated List in C#
  3. Using the StringBuilder Method to Create a Comma Separated List in C#
How to Create a Comma Separated List in C#

This tutorial will demonstrate how to create a comma-separated list from containers such as an IList<string or an IEnumerable<string> using either string.Join(), LINQ Aggregate, or StringBuilder.

Using the String.Join() Method to Create a Comma Separated List in C#

The simplest way to join the values of a container would be the string.Join(). The string.Join() function takes all of the values in a collection and concatenates them with any defined separator. Using this method, you can not only make lists separated by commas but any other delimiter as well.

string joined_str = string.Join(separator, source);

The separator parameter must be a string while the source can be a collection of any datatype.

Example:

using System;
using System.Collections.Generic;

namespace StringJoin_Example {
  class Program {
    static void Main(string[] args) {
      // Initialize the IList
      IList<Int32> list_strings = new List<Int32> { 1, 2, 3 };
      // Join the IList with a comma
      string joined_list = string.Join(", ", list_strings);
      // Print the results
      Console.WriteLine("From List: " + joined_list);

      // Initialize the IEnumerable
      IEnumerable<string> enum_strings =
          new List<string>() { "Enum Sample 1", "Enum Sample 2", "Enum Sample 3" };
      // Join the IEnumerable with a semi colon
      string joined_enum = string.Join("; ", enum_strings);
      // Print the results
      Console.WriteLine("From Enumerable: " + joined_enum);

      Console.ReadLine();
    }
  }
}

In the example above, we created two different sources: a list of integers and an enumerable list of strings. We then joined them using the same string.Join() method with two different separators and then printed the resulting strings to the console.

Output:

From List: 1, 2, 3
From Enumerable: Enum Sample 1; Enum Sample 2; Enum Sample 3

Using the LINQ Aggregate Method to Create a Comma Separated List in C#

Another option for joining a collection’s values would be to use the LINQ Aggregate method. While convenient to code, this is considered inefficient, especially the larger the input. This method will also throw an error if the input count is less than one, so more error handling may be required to ensure that this runs each time smoothly.

string joined_str = input.Aggregate((x, y) => x + ", " + y);

Like the first method, you can use any string input as a separator, but this method will expect the result value to be the same as its input. For example, if the input collection was an integer list, this function would not work.

Example:

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqAggregate_Example {
  class Program {
    static void Main(string[] args) {
      // Initialize the IList
      IList<string> list_strings =
          new List<string> { "List Sample 1", "List Sample 2", "List Sample 3" };
      // Join the IList with a comma using LINQ Aggregate
      string joined_list = list_strings.Aggregate((x, y) => x + ", " + y);
      // Print the results
      Console.WriteLine("From List: " + joined_list);

      // Initialize the IEnumerable
      IEnumerable<string> enum_strings =
          new List<string>() { "Enum Sample 1", "Enum Sample 2", "Enum Sample 3" };
      // Join the IEnumerable with a semi colon using LINQ Aggregate
      string joined_enum = enum_strings.Aggregate((x, y) => x + "; " + y);
      // Print the results
      Console.WriteLine("From Enumerable: " + joined_enum);

      Console.ReadLine();
    }
  }
}

In the example above, we joined the two collections by using the LINQ Aggregate method. The variables x and y can be changed to any variable name you like. The idea behind this method is that it concatenates the previous string to the next string should there still be values to join.

Output:

From List: List Sample 1, List Sample 2, List Sample 3
From Enumerable: Enum Sample 1; Enum Sample 2; Enum Sample 3

Using the StringBuilder Method to Create a Comma Separated List in C#

The last option that we will discuss is the StringBuilder method. Compared to the other two methods, this one requires a bit more code to be written but allows for a lot more customization. Within the function, you can add more steps to modify the values should you like to. For example, if you pass a list of datetimes, you could combine the values while using a specified DateTime format.

Example:

using System;
using System.Collections.Generic;
using System.Text;

namespace StringBuilder_Example {
  class Program {
    static void Main(string[] args) {
      // Initialize the IList
      IList<string> list_strings =
          new List<string> { "List Sample 1", "List Sample 2", "List Sample 3" };
      // Join the IList with a comma using the StringBuilder method
      string joined_list = join_collection(", ", list_strings);
      // Print the results
      Console.WriteLine("From List: " + joined_list);

      // Initialize the IEnumerable
      IEnumerable<string> enum_strings =
          new List<string>() { "Enum Sample 1", "Enum Sample 2", "Enum Sample 3" };
      // Join the IEnumerable with a semi colon using the StringBuilder method
      string joined_enum = join_collection("; ", enum_strings);
      // Print the results
      Console.WriteLine("From Enumerable: " + joined_enum);

      Console.ReadLine();
    }

    static string join_collection<T>(string separator, IEnumerable<T> values) {
      // Initialize StringBuilder
      StringBuilder sb = new StringBuilder();

      // Intialize the item counter
      int ctr = 0;
      foreach (T item in values) {
        string sep = "";
        if (ctr > 0) {
          // If the first item from the value collection has already been added, use the specified
          // separator This is to avoid printing the separator as the first value of the string
          sep = separator;
        }

        // Append the separator and the value as a string
        sb.Append(sep);
        sb.Append(item.ToString());
        ctr++;
      }

      // Return the built string
      return sb.ToString();
    }
  }
}

In the example above, we joined the collections using our custom function join_collection, which accepts a string separator and an enumerable collection. The values are then joined together using a StringBuilder and appending the separator and collection values.

Output:

From List: List Sample 1, List Sample 2, List Sample 3
From Enumerable: Enum Sample 1; Enum Sample 2; Enum Sample 3

Related Article - Csharp List