List和string之间的互相转换

List和string之间的互相转换

我们在开发中经常会用List<string>来保存一组字符串,比如下面这段代码:
List<string> studentNames = new List<string>();

studentNames.Add("John");
studentNames.Add("Mary");
studentNames.Add("Rose");

可是有时候,我们要从中获取一个字符串,字符串的内容就是集合中的内容,但是要用逗号隔开,下面的办法可以实现:
string.Join(", ", studentNames.ToArray())

 上面这条语句,返回的结果应该是下面这个样子:
John, Mary, Rose

下面让我们来做个反向工程,从string转换成List<string>
string result = string.Join(", ", studentNames.ToArray());

List<string> newStudentNames = new List<string>(result.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries));

foreach (string s in newStudentNames)
{
    System.Diagnostics.Debug.WriteLine(s);
}

输出结果如下:
John
Mary
Rose
岁月冲掉尘埃,淘汰虚无;待青春过后,褪尽芳华,是否有人珍惜遗留下的坦然和从容。
原文地址:https://www.cnblogs.com/lushulihuachenyu/p/3487418.html