You can do this to clear all elements between any two other elements:
var strings = new[] { "foo", "str1", "str2", ... "bar", ... "baz" }; var between = strings.SkipWhile(s => s != "foo").Skip(1) .TakeWhile(s => s != "bar");
If you want to get everything between "foo" and "baz" except for "bar", use this (assuming the order is "foo", "bar", "baz"):
var strings = new[] { "foo", "str1", "str2", ... "bar", ... "baz" }; var between = strings.SkipWhile(s => s != "foo").Skip(1) .TakeWhile(s => s != "baz") .Where(s => s != "bar");
Or, if itβs convenient for you to use Linq queries with side effects, you can do this to split your input list into specific βstopβ words:
var stops = new[] { "foo", "bar", "baz" }; var strings = new[] { "foo", "str1", "str2", "bar", "str3", "baz" }; var p = -1; var partitions = from s in strings let i = Array.IndexOf(stops, s) group s by p = i == -1 ? p : i into g where g.Key == 0 || g.Key == 1 select g.Skip(1);
Or a little more efficient (since it stops processing after the third stop word):
var partitions = (from s in strings let i = Array.IndexOf(stops, s) group s by p = i == -1 ? p : i) .SkipWhile(g => g.Key < 0) .Take(2) .Select(g => g.Skip(1));
Now this method is a little rough around the edges, and it is somewhat inconvenient when it comes to elements before "foo" or after "baz", but if you are only looking for elements between "foo" and "baz", it should work for you. It has the added benefit that stop word order does not affect the results.