我需要经常转换“串块”(一个包含字符串的字符返回,例如从文件或一个文本框)成List<string>
。什么是将返回字符分隔的字符串转换为列表的最佳方式<string>?
什么是比以下ConvertBlockToLines方法更优雅的方式吗?
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestConvert9922
{
class Program
{
static void Main(string[] args)
{
string testBlock = "line one" + Environment.NewLine +
"line two" + Environment.NewLine +
"line three" + Environment.NewLine +
"line four" + Environment.NewLine +
"line five";
List<string> lines = StringHelpers.ConvertBlockToLines(testBlock);
lines.ForEach(l => Console.WriteLine(l));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List<string> ConvertBlockToLines(this string block)
{
string fixedBlock = block.Replace(Environment.NewLine, "§");
List<string> lines = fixedBlock.Split('§').ToList<string>();
lines.ForEach(s => s = s.Trim());
return lines;
}
}
}
您不需要传递'StrringSplitOptions.None',因为这是Split()的默认行为。 – 2010-02-24 13:38:26
@Seth:你错了,在发送'string []'(而不是'char []')时必须通过它。在这种情况下,你可能并不清楚Environment.NewLine是一个'string []'。所以你的评论有助于强调它是好的是冗长:) – 2010-02-24 13:44:59
@silky:我的坏,你说得对。这就是我匆匆发表评论的原因... – 2010-02-24 13:55:40