我有一个字符串:
string data =
"item1 actived
item2 none
item special I none
item special II actived"
您可以在数据中看到4行。 我需要将一个字符串拆分为List项,如下所示:
item[0]={Name=item1, Status=actived}
item[1]={Name=item2, Status=none}
item[2]={Name=item Special I, Status=none}
item[3]={Name=item Special II, Status=actived}
我试过了:
var s = SplitReturn(data);
public string[] SplitReturn(string name)
{
return name.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
如何在字符串中拆分空格然后转换为List?
答案 0 :(得分:3)
string data =
@"item1 actived
item2 none
item special I none
item special II actived";
var result = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => {
int lastSpace = item.LastIndexOf(' ');
return new
{
Name = item.Substring(0, lastSpace).Trim(),
Status = item.Substring(lastSpace, item.Length - lastSpace).Trim()
}; }).ToList();