List和string之间的互相转换

http://blog.163.com/zhaoyanping_1125/blog/static/20132915320120711355117/

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

studentNames.Add("John");
studentNames.Add("Mary");
studentNames.Add("Rose");
1、List用指定字符分割,得到String

可是有时候,我们要从中获取一个字符串,字符串的内容就是集合中的内容,但是要用逗号隔开,下面的办法可以实现:
string.Join(", ", studentNames.ToArray())
上面这条语句,返回的结果应该是下面这个样子:
John, Mary, Rose

StringUtils.join(studentNames.ToArray(),",");

2、String通过某个字符split,创建list。

string result = "Jon,Mary,Rose";

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

猜你喜欢

转载自jackleechina.iteye.com/blog/2267348