C#:List<string>特定格式输出

在C#中,如果有一个`List<string>`类型的列表,并且想要以特定格式(例如,用`|`分隔每个字符串)输出这些字符串,可以使用多种方法。下面是一些实现这个目标的方法:

方法1:使用`String.Join`

`String.Join`方法非常适合用来将集合中的元素连接成一个字符串,可以指定一个分隔符。

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

List<string> list = new List<string> { "apple", "banana", "cherry" };

string result = String.Join("|", list);

Console.WriteLine(result);

}

}

方法2:使用`foreach`循环

如果不想使用`String.Join`,也可以通过遍历列表并手动构建字符串。

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

List<string> list = new List<string> { "apple", "banana", "cherry" };

string result = "";

foreach (var item in list)

{

result += item + "|";

}

// 移除最后一个多余的'|'字符

if (!string.IsNullOrEmpty(result))

{

result = result.Substring(0, result.Length - 1);

}

Console.WriteLine(result);

}

}

```

方法3:使用LINQ的`Aggregate`方法

LINQ的`Aggregate`方法也是一个很好的选择,它可以让你在单个表达式中完成连接和分隔符的添加。

using System;

using System.Collections.Generic;

using System.Linq;

class Program

{

static void Main()

{

List<string> list = new List<string> { "apple", "banana", "cherry" };

string result = list.Aggregate((i, j) => i + "|" + j);

Console.WriteLine(result);

}

}

相关推荐
1-1=03 小时前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
叼烟扛炮12 小时前
[LangChain] 学习笔记(06):突破大模型限制——结构化输出(Structured Output)
windows·笔记·学习·langchain
Thneonl1 天前
桌宠穿透不是一行 SetWindowLong
windows·程序员
艺杯羹2 天前
Windows原生软件锁设计:从暴力杀进程丢数据到零轮询事件驱动架构
windows·系统架构·开源·开源软件·内存管理·开源协议
波力海苔夹心脆6752 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端2 天前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭
csdn_aspnet2 天前
Redis 入门:Windows、Mac安装指南
数据库·windows·redis·缓存·mac
Risehuxyc2 天前
C# 选用更流行的语言版本
c#
淡海水3 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc
没差c3 天前
winsw将jar、nginx等注册为Windows服务
windows·nginx·jar