ZetCode

C# List 转字符串

上次修改时间:2025 年 5 月 14 日

本教程演示了如何在 C# 中将 List 转换为字符串。

要在 C# 中将元素列表转换为单个字符串,我们可以使用 string.Join 方法、StringBuilder 类、Enumerable.Aggregate 方法或字符串连接运算符。

string.Join 方法组合集合或数组的元素,并在每个元素之间插入指定的分隔符。 StringBuilder 类有效地动态构建字符串。 Enumerable.Aggregate 方法在值序列上应用累加器函数。

C# 使用 + 运算符连接字符串,但对于大型列表,效率可能较低。

使用 string.Join

以下示例使用 string.Join 方法将列表转换为字符串。

Program.cs
List<string> words = ["a", "visit", "to", "London"];
var res = string.Join("-", words);

Console.WriteLine(res);

此示例通过用连字符连接单词列表来创建一个 slug。即使对于大型列表,此方法也很有效,因为它只分配一次结果字符串。

$ dotnet run
a-visit-to-London

使用 StringBuilder

此示例演示了如何使用 StringBuilder 类从列表构建字符串。

Program.cs
using System.Text;

List<string> words = ["There", "are", "three", "chairs", "and", "two",
    "lamps", "in",  "the", "room"];

var builder = new StringBuilder();

foreach (var word in words)
{
    builder.Append(word).Append(' ');
}

Console.WriteLine(builder.ToString());

代码使用 foreach 循环遍历列表,将每个单词和一个空格附加到 StringBuilder 对象。 ToString 方法将结果转换为字符串。 由于 StringBuilder 的可变性,这种方法对于大型列表非常有效。

$ dotnet run
There are three chairs and two lamps in the room

使用 Enumerable.Aggregate

下一个示例使用 Enumerable.Aggregate 方法将列表转换为字符串。

Program.cs
List<string> words = ["There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"];

var res = words.Aggregate((total, part) => $"{total} {part}");
Console.WriteLine(res);

此示例在累加器函数中使用字符串插值,通过将每个单词与空格连接起来来构建字符串。 虽然方便,但对于大型列表,Aggregate 的效率低于 StringBuilderstring.Join

使用字符串连接

此示例使用字符串连接运算符从列表构建字符串。

Program.cs
List<string> words = ["There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"];

string res = string.Empty;

words.ForEach(word => {

    res += $"{word} ";
});

Console.WriteLine(res);

代码使用 ForEach 方法迭代列表,使用 += 运算符将每个单词和一个空格附加到结果字符串。 这种方法简单易懂。 但是,对于大型列表,重复的字符串连接效率可能较低。 对于大型列表,由于性能开销,不建议使用此方法。

使用 string.Concat

将列表转换为字符串的另一种方法是使用 string.Concat 方法。 此方法连接列表的所有元素,没有任何分隔符。 当不需要分隔符时,这是一种快速连接列表元素的方法。 此方法有效地将多个字符串组合在一起。

Program.cs
List<string> words = ["There", "are", "three", "chairs", "and", "two", 
    "lamps", "in",  "the", "room"];

var res = string.Concat(words);
Console.WriteLine(res);

此示例使用 string.Concat 将列表的所有元素连接成一个字符串,没有任何分隔符。 如果您需要分隔符,请改用 string.Join。 对于大型列表,此方法非常有效,因为它只分配一次结果字符串。

来源

string.Join 方法

本教程演示了在 C# 中将列表转换为字符串的各种方法。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程