0

I need to convert string to IEnumerable<string> by every newline character.

I just want the same functionality as File.ReadLines without loading any file, rather taking it from a previously loaded string.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ragedcoder
  • 59
  • 10

2 Answers2

0

You could split it according to the newline character:

String[] lines = fileContenets.Split('\n');
Mureinik
  • 277,661
  • 50
  • 283
  • 320
0

String.Split can split your string and give you string[]

Usage

string someString = ...;
string[] lines = someString.Split('\n');
IEnumerable<string> linesAsEnumerable = lines;

DoSomethingWithLines(linesAsEnumerable);
JL0PD
  • 2,512
  • 1
  • 9
  • 18
  • Or even better `IEnumerable lines = someString.Split(Environment.NewLine);`. – Alejandro Jul 02 '21 at 15:06
  • @Alejandro It has to be `Split(Environment.NewLine, StringSplitOptions.None)` because `Environment.NewLine` is a `string` and there is no override of `Split` that just takes a single `string` argument. – juharr Jul 02 '21 at 15:07
  • @Alejandro, yes, but I've created `string[]` variable to show actual return type. `IEnumerable` slower to process than raw array – JL0PD Jul 02 '21 at 15:10
  • 1
    @Alejandro The question specifically specified the newline character, not the OS's new line character sequence. Given that they're not reading a file, there's no reason to assume the OS's new line string is what that string uses. – Servy Jul 02 '21 at 15:11