在 C# 中将 List<string>转换为字符串
在本教程中,我们将讨论在 C# 中把 List<string>
转换为字符串变量的方法。
使用 C# 中的 Linq 方法将 List<string>
转换为字符串
Linq 或语言集成查询可以在 C# 中执行健壮的文本操作。Linq 具有 Aggregate()
函数,可以将字符串列表转换为字符串变量。以下代码示例向我们展示了如何使用 C# 中的 Linq 方法将 List<string>
转换为字符串。
using System;
using System.Collections.Generic;
using System.Linq;
namespace list_to_string
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>() { "Ross", "Joey", "Chandler" };
string joinedNames = names.Aggregate((x, y) => x + ", " + y);
Console.WriteLine(joinedNames);
}
}
}
输出:
Ross, Joey, Chandler
我们创建字符串列表 names
,并在 names
中插入值 { "Ross", "Joey", "Chandler" }
。然后,使用 Aggregate()
函数将 names
列表中的字符串用 ,
作为它们之间的分隔符连接起来。
此方法非常慢,不建议使用。这与运行 foreach
循环并连接每个元素相同。
使用 C# 中的 String.Join()
函数将 List<string>
转换为字符串
String.Join(separator, Strings)
函数可以在 C# 中用指定的 separator
连接 Strings
。String.Join()
函数返回通过将 Strings
参数与指定的 separator
连接而形成的字符串。
下面的代码示例向我们展示了如何使用 C# 中的 String.Join()
函数将 List<string>
转换为字符串。
using System;
using System.Collections.Generic;
namespace list_to_string
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>() { "Ross", "Joey", "Chandler" };
string joinedNames = String.Join(", ", names.ToArray());
Console.WriteLine(joinedNames);
}
}
}
输出:
Ross, Joey, Chandler
我们创建字符串列表 names
,并在 names
中插入值 { "Ross", "Joey", "Chandler" }
。然后,使用 C# 中的 String.Join()
函数将 names
列表中的字符串用 ,
作为它们之间的分隔符连接起来。
此方法快得多,并且比以前的方法更好。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。