List和string之间的互相转换

来源:互联网 发布:网络诈骗能把钱追回吗 编辑:程序博客网 时间:2024/05/21 22:37

我们在开发中经常会用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
原创粉丝点击