What is the best way to convert a string separated by return chars into a List?

前端 未结 6 711
谎友^
谎友^ 2021-01-17 16:46

I need to often convert a \"string block\" (a string containing return characters, e.g. from a file or a TextBox) into List

6条回答
  •  天命终不由人
    2021-01-17 17:07

    Have you tried splitting on newline/carriage return and using the IEnumerable ToList extension?

    testBlock.Split( new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries )
             .ToList()
    

    If you want to keep empty lines but may have both linefeed and carriage return.

    textBlock.Replace( "\r\n", "\n" ).Replace( "\r", "\n" ).Split( '\n' ).ToList();
    

提交回复
热议问题