How To Convert a List to a String in C#

Introduction

The following code sample demonstrates how to convert a C# list of strings into a single string in C#. The code examples are written in C# 10 and .NET 6.0. 

There are multiple ways to convert lists of strings into a single string in C#.

// C# List of strings
List<string> alphabets = new List<string>(){ "A", "B", "C", "D", "Eโ€};

For Loop

If we want to write some logic while concatenating the strings, we can implement through for loop.

string result = "";
for (int i = 0; i < alphabets.Count; i++) {
    result = result + alphabets[i] + ",";
}
Console.Write("String Concatenation With For Loop: " + result);

Result

String Concatenation With For Loop: A,B,C,D,E,F

String.Join

We can simply convert into a single string using string.join method. The join method concatenate a list of strings into a single string.

string result = String.Join(",", alphabets);

Result

A,B,C,D,E,F

Using LINQ

We can also use LINQ query to get a single string from a list

string result = alphabets.Aggregate("", (current, s) => current + (s + ","));

Result

A,B,C,D,E,F

An aggregate function is used for an accumulator function over a sequence. This function will work with System.Collections.Generic.IEnumerable collection.

We can also join any column of an entity.

string firstNames = string.Join(",", EmpList.Select(x => x.FirstName));
string result = String.Join(", ", EmpList.Select(p => p.LastName));

Summary

The purpose of this article is to help beginners with multiple ways to solve their problems while concatenating strings into a single result. Happy Coding!! ๐Ÿ˜Š


Similar Articles