将返回字符分隔的字符串转换为List <string>的最佳方法是什么?

Edw*_*uay 10 c# string generics

我需要经常将"字符串块"(包含返回字符的字符串,例如从文件或TextBox)转换为List<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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

the*_*oop 20

List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
Run Code Online (Sandbox Code Playgroud)

这会将连续的换行符保留为空字符串(请参阅StringSplitOptions)

  • @Seth:你错了,你必须传递它,当发送一个`string []`,(而不是`char []`).在这种情况下,你可能并不明白Environment.NewLine是一个`string []`.因此,您的评论有助于突出显示详细是好的:) (3认同)