DaFunkyAlex DaFunkyAlex - 3 months ago 8
C# Question

Grab a portion of List<string>

I have a List, looking like this:

some headline content
a subheadline containing the keyword
1 2015-05-05 some data
2 2015-05-05 some data
3 2015-05-05 some data
some content
a subheadline containing another keyword
useless stuff


So now I want to grab all the stuff between "keyword" and "another keyword".
Maybe I should find the index of "keyword" and "another keyword" and use .GetRange(), but is there a more elegant way to do this with e.g. LINQ?

Answer

You can use SkipWhile and TakeWhile

var newList = list.SkipWhile(line => !line.Contains("keyword"))
                  .Skip(1)
                  .TakeWhile(line => !line.Contains("another keyword"))
                  .ToList();
Comments