c# - How to get several lines from a text file? -
i have text file:
hh sdf.... 1 line empty line other line goal apf ee 1 line goal
list<string> goo = new list<string>(); system.io.streamreader file = new system.io.streamreader("text.txt"); while (file.endofstream != true) { string s = file.readline(); if (s.contains("something")) { goo.add(s); } }
i want lines after something
, until goal
. there many something
, goal
in file. should use array or somthing...?
i'll offer linq-style solution. first, simple helper extension method picking subranges out of ienumerable<t>
:
public static class enumerablehelper { public static ienumerable<list<t>> getwindows<t>( ienumerable<t> source, func<t, bool> begin, func<t, bool> end) { list<t> window = null; foreach (var item in source) { if (window == null && begin(item)) { window = new list<t>(); } if (window != null) { window.add(item); } if (window != null && end(item)) { yield return window; window = null; } } } };
now can windows of text you're interested in this:
list<list<string>> windows = file.readlines("file.txt") .getwindows( line => line.contains("something"), line => line.contains("goal")) .tolist();
each item in windows
list of lines of text correspond single "something...goal" pair.
Comments
Post a Comment