DaFunkyAlex
DaFunkyAlex

Reputation: 1969

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?

Upvotes: 30

Views: 1380

Answers (3)

Eser
Eser

Reputation: 12546

You can use SkipWhile and TakeWhile

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

Upvotes: 58

user2545071
user2545071

Reputation: 1410

List<String> stringsColl=new List<String>();
strinsColl.Add(..some you strs);
...
foreach(var str in stringsColl)
{
  if(str.Contains("keyword")
   {
      ...do some work
   }
}

Upvotes: -5

Mark Jansen
Mark Jansen

Reputation: 1509

yourList.Skip(10).Take(5);

This will skip 10 items, then return the next 5.

But this will only work if you already know the indexes of the keywords.

Upvotes: 2

Related Questions