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

posted on 2013-12-23 14:43  褪尽芳华  阅读(223)  评论(0编辑  收藏  举报